Table of contents
- Types of tests
- Testing libraries
- Unit tests
- Integration tests
- Automation testing
- Setting up jest
- Async tests
- Mocks and spies
- Enzyme
- Testing stateful components
- Testing connected components
- Testing reducers
- Testing actions
Examples
Github example of simple JS unit test 1 React unit test example with robofriends app 2 Jest Cheatsheet
Types of tests
- Unit: Cover small pure function. Don’t test the contract, like if signin function is calling load function, don’t test the load function.
- Integration: They can be brittle and are much harder to write. Its hard to say when 100% completion is achieved.
- Automation: Hardest to setup as they will run on different machines and browsers. There are many services, like cypress
Writing test
The setup is done bycreate_react_app
Jest
Jest is a delightful JavaScript Testing Framework with a focus on simplicity.
It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more!
- Its is fast because of snaphosts which keep track of large objects.
- Parallel test cases running to maximize performance.
- it and expect supported.
- Code coverage.
Jest getting started
npm install --save-dev jest
Let’s get started by writing a test for a hypothetical function that adds two numbers. First, create a sum.js file:
function sum(a, b) { return a + b;}module.exports = sum;
Then, create a file named sum.test.js. This will contain our actual test:
const sum = require('./sum');test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3);});
Add the following section to your package.json:
{ "scripts": { "test": "jest" }}
Finally, run yarn test or npm test and Jest will print this message:
PASS ./sum.test.js✓ adds 1 + 2 to equal 3 (5ms)
You just successfully wrote your first test using Jest!
Enzyme vs React testing library
Alternate to Enzyme is React testing library. Enzyme seems better, learn only one. Seems to be a product ofAirbnb Enzyme gives mostly three things:
- shallow
- mount
- render Test to make sure component renders:
import { Shallow, mount, render } from 'enzyme';
import React from 'react';
import Card from './Card';
it('expect to render Card component', () => {
expect(shallow(<Card />).length).toEqual(1)
});