- Intro
- Basic test (test state and props)
- Testing user interaction
- Testing whether a class method is called or not
- Things to remember
I am assuming you already have a testing environment set up with all the tools installed: karma + webpack and enzyme.
If not, these are good resources:
We want to test the Button component defined in our react component guide.
import React from 'react';
import { shallow } from 'enzyme';
import Button from './Button';
function render(props) {
return shallow(<Button {...props} />);
}
describe("Button component tests", () => {
it("renders the prop correctly", () => {
props = {
buttonName: 'mockButton'
};
const renderedComp = render(props);
expect(renderedComp.props().buttonName).toEqual(props.buttonName);
});
it("has correct initial state", () => {
const renderedComp = render({});
expect(renderedComp.state().numOfClicks).toEqual(0);
});
});
it("increase numOfClick by 1 when button is clicked", () => {
const renderedComp = render({});
expect(renderedComp.state().numOfClicks).toEqual(0);
const button = renderedComp.find('button');
button.simulate('click');
expect(renderedComp.state().numOfClicks).toEqual(1);
});
Always try to mock user interaction as much as possible i.e. simulating a click.
it("increase numOfClick by 1 when button is clicked", () => {
const functionToBeCalled = spyOn(Button.prototype, 'handleClick')
const renderedComp = render({});
const button = renderedComp.find('button');
button.simulate('click');
expect(functionToBeCalled).toHaveBeenCalled();
});
- You can have nested
describe
blocks. Your describe block should act like a test suite. - Each
it
block should test one piece of functionality. - Use
beforeAll()
andbeforeEach()
. shallow
rendering will get the job done 90% of the time. But, there are times when you need to usemount
to do a full mounting of your react component in your tests. To learn more about their differences, visit here.