[React] Test

Test Tools

  • Test Runner: Executes tests and provide validation library Jest
  • Test Utilities: “Simulates” the React App (mounts components, allows you to dig into the DOM): Enzyme

What to test

  • Don’t test complex connections
  • Don’t test the library

  • Do test isolated units

  • Do test your conditional outputs

Start test

1
2
3
npm install --save enzyme
npm i -save react-test-renderer
npm i -save enzyme-adapter-react-16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// NavigationItems.test.js
import React from 'react';
import {configure, shallow} from 'enzyme'; // shallow is used to render the DOM
import Adapter from 'enzyme-adapter-react-16';
import NavigationItems from './NavigationItems';
import NavigationItem from './NavigationItem';

configure({adapter: new Adapter()}); // Connect with enzyme

describe('<NavigationItems />', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<NavigationItems />); // setup component
});

it('should render two <NavigationItem /> elements if not authenticated', () => {// it() allows us to write individual test
expect(wrapper.find(NavigationItem)).tohaveLength(2);
});

it('should render three <NavigationItem /> elements if authenticated', () => {
wrapper.setProps({isAuthenticated: true}); // Add props
expect(wrapper.find(NavigationItem)).toHaveLength(3);
});

it('should render three <NavigationItem /> elements if authenticated', () => {
wrapper.setProps({isAuthenticated: true}); // Add props
expect(wrapper.contains(<NavigationItem link="/logout">)).toEqual(true);
});
});

Each test runs independently.
Run test npm run test

Test container components

In container component, export the name of component.

1
2
// Component.js
export class BurgerBuilder extends Component {...}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Component.test.js
import { BurgerBuilder } from './BurgerBuilder';
import React from 'react';
import {configure, shallow} from 'enzyme'; // shallow is used to render the DOM
import Adapter from 'enzyme-adapter-react-16';
import BuildControls from '../../components/Burger/BuildControls/BuildControls';

describe('<BurgerBuilder />', () => {
let wrapper;

beforeEach(() => {
wrapper = shallow(<BurgerBuilder onInitIngredients={() => {}}/>);
});

it('should render <BuildControls /> when receiving ingredients', () => {
wrapper.setProps({ings: {salad: 0}});
expect(wrapper.find(BuildControls)).toHaveLength(1);
})
})