Multiple React components

So, what if there are multiple React components, and some components have already been tested? If we create snapshot testing, that will simply collect a bunch of snapshots. Isn’t that overkill?

Yes; absolutely. This is when mocking shines. An example is better than a thousand words. Let's consider the following React component. Consider a HeaderNav component that contains a Logo component, a Header component, and social media link components. We are using these components in our HeaderNav component, and we know that we have already tested the Header component. To avoid this, we can just mock the component that we do not want to include in the snapshot:

import React from "react";
import Link from "react-router-dom/Link";
import Header from "./Header";
import SocialMediaLinks from "./SocialMediaLinks";
import Logo from "./Logo";
const HeaderNav = () => (
<div>
<Logo />
<Header />
<SocialMediaLinks />
</div>
);
export default HeaderNav;

Our test can be as simple as the following:

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

Note that we are mocking four components here: the Link from react-router-dom, Header, SocialMediaLinks, and Logo. We should note that when mocking any component, the first argument is the path to the file. Here, "../Logo", says to look for the file in one directory, outside of the current folder:

jest.mock("../Logo", () => "Logo");

In order to understand the difference between testing the components with and without mocking, try to run the test by removing all of the mocking files and update your snapshot, in order to pass your test. We can update the snapshot by using the test command, as follows:

yarn test --updateSnapshot
..................Content has been hidden....................

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