Skip to content

Latest commit

 

History

History
 
 

using-babel

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

example: using-babel

Component testing for projects using Babel config

Example component test

Usage

  1. Make sure the root project has been built .
# in the root of the project
npm install
npm run build
  1. Run npm install in this folder to symlink the @cypress/react dependency.
# in this folder
npm install
  1. Start Cypress
npm run cy:open
# or just run headless tests
npm test

Specs

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
}

Mocking

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 />)
  })
})