Skip to content

pgroot91/cypress-react-unit-test

 
 

Repository files navigation

cypress-react-unit-test Build Status Cypress.io tests renovate-app badge

A little helper to unit test React components in the open source Cypress.io E2E test runner ALPHA

TLDR

Known problems

  • some DOM events are not working when running all tests at once #4
  • cannot mock server XHR for injected components #5
  • cannot spy on window.alert #6

Install

Requires Node version 6 or above.

npm install --save-dev cypress cypress-react-unit-test

Use

// import the component you want to test
import { HelloState } from '../../src/hello-x.jsx'
import React from 'react'
import { mount } from 'cypress-react-unit-test'
describe('HelloState component', () => {
  it('works', () => {
    // mount the component under test
    mount(<HelloState />)
    // start testing!
    cy.contains('Hello Spider-man!')
    // mounted component is returned from Cypress.component()
    Cypress.component().invoke('setState', {name: 'React'})
    Cypress.component().its('state').should('deep.equal', {
      name: 'React'
    })
    // check if GUI has rerendered
    cy.contains('Hello React!')
  })
})

Unit testing React components

Transpilation

How can we use features that require transpilation? Using @cypress/webpack-preprocessor. You can use cypress/plugins/index.js to configure any transpilation plugins you need.

For example, to enable class properties:

// cypress/plugins/index.js
const webpack = require('@cypress/webpack-preprocessor')
const webpackOptions = {
  module: {
    rules: [
      {
        test: /\.(js|jsx|mjs)$/,
        loader: 'babel-loader',
        options: {
          presets: ['env', 'react'],
          plugins: ['transform-class-properties'],
        },
      }
    ]
  }
}

const options = {
  // send in the options from your webpack.config.js, so it works the same
  // as your app's code
  webpackOptions,
  watchOptions: {}
}

module.exports = on => {
  on('file:preprocessor', webpack(options))
}

Install dev dependencies

npm i -D @cypress/webpack-preprocessor \
  babel-loader babel-preset-es2015 babel-preset-react \
  babel-plugin-transform-class-properties

And write a component using class properties

import React from 'react'

export class Transpiled extends React.Component {
  state = {
    count: 0
  }

  // ...
}

Examples

All components are in src folder. All tests are in cypress/integration folder.

Large examples

Related tools

Same feature for unit testing components from other framesworks using Cypress

About

Unit test React components using Cypress

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 98.7%
  • HTML 1.3%