|
| 1 | +# example: using-babel |
| 2 | + |
| 3 | +> Component testing for typescript projects using Babel config with `@babel/preset-typescript` |
| 4 | +
|
| 5 | + |
| 6 | + |
| 7 | +## Usage |
| 8 | + |
| 9 | +1. Make sure the root project has been built . |
| 10 | + |
| 11 | +```bash |
| 12 | +# in the root of the project |
| 13 | +npm install |
| 14 | +npm run build |
| 15 | +``` |
| 16 | + |
| 17 | +2. Run `npm install` in this folder to symlink the `cypress-react-unit-test` dependency. |
| 18 | + |
| 19 | +```bash |
| 20 | +# in this folder |
| 21 | +npm install |
| 22 | +``` |
| 23 | + |
| 24 | +3. Start Cypress |
| 25 | + |
| 26 | +```bash |
| 27 | +npm run cy:open |
| 28 | +# or just run headless tests |
| 29 | +npm test |
| 30 | +``` |
| 31 | + |
| 32 | +## Specs |
| 33 | + |
| 34 | +See spec files [src/\*.spec.js](src). The specs are bundled using [babel.config.js](babel.config.js) settings via [cypress/plugins/index.js](cypress/plugins/index.js) file that includes file preprocessor. |
| 35 | + |
| 36 | +```js |
| 37 | +// let's bundle spec files and the components they include using |
| 38 | +// the same bundling settings as the project by loading .babelrc |
| 39 | +const preprocessor = require('cypress-react-unit-test/plugins/babelrc') |
| 40 | +module.exports = (on, config) => { |
| 41 | + preprocessor(on, config) |
| 42 | + // IMPORTANT to return the config object |
| 43 | + // with the any changed environment variables |
| 44 | + return config |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +## Mocking |
| 49 | + |
| 50 | +During test runs, there is a Babel plugin that transforms ES6 imports into plain objects that can be stubbed using [cy.stub](https://on.cypress.io/stub). In essence |
| 51 | + |
| 52 | +```ts |
| 53 | +// component imports named ES6 import from "calc.js |
| 54 | +import { getRandomNumber } from './calc' |
| 55 | +const Component = () => { |
| 56 | + // then calls it |
| 57 | + const n = getRandomNumber() |
| 58 | + return <div className="random">{n}</div> |
| 59 | +} |
| 60 | +``` |
| 61 | + |
| 62 | +The test can mock that import before mounting the component |
| 63 | + |
| 64 | +```js |
| 65 | +import Component from './Component' |
| 66 | +import * as calc from './calc' |
| 67 | +describe('Component', () => { |
| 68 | + it('mocks call from the component', () => { |
| 69 | + cy.stub(calc, 'getRandomNumber') |
| 70 | + .returns(777) |
| 71 | + mount(<Component />) |
| 72 | + }) |
| 73 | +}) |
| 74 | +``` |
0 commit comments