Skip to content

Adding testing to a plugin

ray-millward-tessella edited this page Mar 14, 2019 · 8 revisions

Adding unit testing

Create React App adds Jest unit tests by default and these are a good starting point. As well as these we want to add Enzyme to be able to do snapshot testing:

npm install --save-dev enzyme enzyme-adapter-react-16 enzyme-to-json

We should then update the test script in package.json to also run coverage

"test": "react-scripts test --env=jsdom --coverage",
"test:watch": "react-scripts test --env=jsdom --watch",

Then add a new jest section to package.json to exclude top level untestable files as well as configuring enzyme as the serialiser:

"jest": {
  "snapshotSerializers": [
    "enzyme-to-json/serializer"
  ],
  "collectCoverageFrom": [
    "src/**/*.{tsx,js,jsx}",
    "!src/index.tsx",
    "!src/serviceWorker.ts",
    "!src/setupTests.js"
  ]
},

Finally, add a src/setupTests.js file that is automatically picked up by CRA and configures Enzyme when running the tests, the contents of which can be found here

Adding end-to-end testing

Install Cypress (https://www.cypress.io/)

npm install cypress

Run cypress open to create a new cypress project in your code base, then add new commands to the scripts section of your package.json to run the e2e tests:

"cy:open": "cypress open",
"cy:run": "cypress run",

Also update the contents of cypress.json:

{
  "baseUrl": "http://127.0.0.1:3000",
  "chromeWebSecurity": false,
  "video": false
}

You need to be running your site at the time you run these tests (i.e. run npm start in a separate console). To make this easier you may want to define an end-to-end server file to serve the built artifacts using node so that no browser is required. For example, see server/e2e-test-server.js

Install cross-env and start-server-and-test:

npm install --save-dev cross-env start-server-and-test

and add the following commands to the scripts section of package.json:

"build:e2e": "cross-env GENERATE_SOURCEMAP=false react-scripts build",
"e2e:serve": "npm run build:e2e && node ./server/e2e-test-server.js",
"e2e:interactive": "start-server-and-test e2e:serve http://localhost:3000 cy:open",
"e2e": "start-server-and-test e2e:serve http://localhost:3000 cy:run",

To run the e2e tests run

npm run e2e

this will run the tests on the command line in a headless mode. To run the e2e tests interactively run

npm run e2e:interactive
Clone this wiki locally