cypress-react-unit-test
A little helper to unit test React components in the open source Cypress.io E2E test runner ALPHA
TLDR
Known problems
Install
Requires Node version 6 or above.
npm install --save-dev cypress cypress-react-unit-test
Use
import { HelloState } from '../../src/hello-x.jsx'
import React from 'react'
describe('HelloState component', () => {
it('works', () => {
cy.mount(<HelloState />)
cy.contains('Hello Spider-man!')
cy.get(HelloState)
.invoke('setState', { name: 'React' })
cy.get(HelloState)
.its('state')
.should('deep.equal', { name: 'React' })
cy.contains('Hello React!')
})
})
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:
const webpack = require('@cypress/webpack-preprocessor')
const webpackOptions = {
module: {
rules: [
{
test: /\.(js|jsx|mjs)$/,
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: ['@babel/plugin-proposal-class-properties'],
},
}
]
}
}
const options = {
webpackOptions,
watchOptions: {}
}
module.exports = on => {
on('file:preprocessor', webpack(options))
}
Install dev dependencies
npm i -D @cypress/webpack-preprocessor \
babel-loader @babel/preset-env @babel/preset-react \
@babel/plugin-proposal-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 frameworks using Cypress