Useful Code Snippets To Help You Test Your React Components

In this tutorial, you will find a number of code examples that cover a range of different testing scenarios that I've needed to write for some of the react.js websites I've worked on.

Basic Snapshot Test Example

Snapshot tests are useful to make sure that people don't accidentally break how a component renders after you have finished with it. The first time a snapshot test is run, a folder will be created in the same directory you run the test called '__snapshots__'. If it runs successfully, you should see a file mirroring your test file except with a .snap extension. If you open this in a text editor, you should see a bunch of HTML. This is the basics of snapshot testing.

    it('basic snapshot test', () => {
        const wrapper = shallow(<div>Hi</div>);
        expect(wrapper).toMatchSnapshot();
    });

After you have updated your JSX, you may find that your snapshot test will fail.  This should be pretty obvious to understand.  You've changed the markup so the final component will now look different.

To correct this is fairly simple.  All you need to do is take a fresh snapshot, check it in and job done!  Simple.  To update a snapshot, simply run jest with the --updateSnapshot, or, simplified -v flag, e.g. yarn test -u

 

Test A Function Has Been Called

One very common thing you may want to test against is that a function has been called when a component has been loaded. One example is that maybe an async request has been made to get some data from an API in your componentMount(). To do this, the easiest way to test this situation is to pass the function in as a prop into the component.

In your test, you can then mock the function, pass it in and then use a method like toHaveBeenCalled()

    it('make sure function called when expected', () => {
        const methodToTest = jest.fn();
        const wrapper = mount(
            <MyComponent methodToTest={methodToTest} >
            </MyComponent>
        );
        expect(wrapper).toHaveBeenCalled();
    });

Testing A Prop/Function Inside Your Component Has The Correct Data

In some situations, just knowing a function is more explicit enough to give you confidence that your component is working as expected. In these situations, you may want to write more explicit test for certain scenarios. You can test these sort cases, using the instance() method, like so:

    it('testing props within a component', () => {
        const wrapper = shallow(<MyComponent  />);
        expect(wrapper.instance().state.componentProp).toBe(true);
    });

Testing What Happens When A Prop Updates After Load

You can also update props within a component using setProps();

 
        const wrapper = shallow(<MyComponent  />);
        wrapper.setProps({ componentProp: true });
        expect(wrapper.instance().state.componentProp).toBeTruthy();

Checking A Button Click Does What You Want It To

Another common test is making sure that after a user has clicked on a button, the component does what you expect it to do. You can do this with the simulate() method, like so:

    it('calls the onClick handler passed when clicked on', () => {
        const clickHandlerMock = jest.fn();
        const wrapper = mount(<MyComponent onClick={clickHandlerMock} />);
        wrapper.simulate('click');
        expect(clickHandlerMock).toHaveBeenCalled();
    });

submit to reddit

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

Back to top