React components and mocking components

Let's consider a React component, as shown in the following code and in the file Header.js:

import React from "react";
import Link from "react-router-dom/Link";
const Header = () => (
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">Services</Link>
</li>
<li>
<Link to="/topics">Contact Us</Link>
</li>
<li>
<Link to="/topics">Login</Link>
</li>
</ul>
);
export default Header;

Testing the component with Jest is simple. We import the component and use snapshot testing:

import React from "react";
import renderer from "react-test-renderer";
import Header from "../Header";
jest.mock("react-router-dom/Link", () => "Link");
it("should render correctly", () => {
const component = renderer.create(<Header />);
expect(component.toJSON()).toMatchSnapshot();
});

There are a few things to note. We used the renderer function to create the component. The renderer function is provided by react-test-renderer, which renders the component. Once we render the component, we can use toMatchSnapshot to test whether the component was rendered as expected. Once you run the test, you will notice that a successful test will create a snapshot folder directly inside of your __test__ folder, namely, __snapshots__. It holds the current snapshot of the component and is used by Jest to test whether your component has changed at a later stage. To find out more about how snapshot testing works, read the official documentation at https://jestjs.io/docs/en/snapshot-testing.

Let's run the test by using the yarn test from a Terminal. By now, you must be familiar with react-router-dom. And now, you also know why mock can be useful in testing. Since we are using Link from react-router-dom, we do not need to test it. We can safely assume that the function is already tested and working. To avoid testing the component, we can simply mock it. Consider mocking named imports, as follows:

import { Router } from 'react-router-dom'

This can easily be done. Jest will automatically serialize a component if it is mocked as a string. So, instead of simply mocking, like in the previous snippet, we can mock as follows:

jest.mock('react-router-dom', () => ({ Router: "Router" }))

That was pretty easy, right?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset