Component testing for projects using Babel config
- Make sure the root project has been built .
# in the root of the project
npm install
npm run build
- Run
npm install
in this folder to symlink the@cypress/react
dependency.
# in this folder
npm install
- Start Cypress
npm run cy:open
# or just run headless tests
npm test
See spec files src/*.spec.js. The specs are bundled using .babelrc settings via cypress/plugins/index.js file that includes file devServer
// let's bundle spec files and the components they include using
// the same bundling settings as the project by loading .babelrc
const devServer = require('@cypress/react/plugins/babel')
module.exports = (on, config) => {
devServer(on, config)
// IMPORTANT to return the config object
// with the any changed environment variables
return config
}
During test runs, there is a Babel plugin that transforms ES6 imports into plain objects that can be stubbed using cy.stub. In essence
// component imports named ES6 import from "calc.js
import { getRandomNumber } from './calc'
const Component = () => {
// then calls it
const n = getRandomNumber()
return <div className="random">{n}</div>
}
The test can mock that import before mounting the component
import Component from './Component.jsx'
import * as calc from './calc'
describe('Component', () => {
it('mocks call from the component', () => {
cy.stub(calc, 'getRandomNumber')
.as('lucky')
.returns(777)
mount(<Component />)
})
})