Last week, we talked about the most basic method for testing a React element, which is smoke testing. Today, we'll talk about a slightly more advanced method, namely shallow rendering test. We will use Jest and Enzyme for this purpose.
Shallow Rendering Test
The main purpose of shallow rendering test is to test a single component isolated from its child components. So you can focus on testing the component without worrying about its children.
To do a shallow rendering test, follow these instructions:
- Start by installing Enzyme and its accompanying packages:
npm install --save enzyme enzyme-adapter-react-16 react-test-renderer
-
You'll need to configure Enzyme first. To do so, create a new file called
setupTests.js
in thesrc
folder of your project. Here's the content of that file:// src/setupTests.js import { configure } from "enzyme"; import Adapter from "enzyme-adapter-react-16"; configure({adapter: new Adapter()});
- We will test a component called
MyCard
, as seen below, which contains a counter and a button to increment the counter. You can also pass a children component to it.
// src/MyCard.js import React from "react"; const MyCard = ({counter, children}) => { const [count, setCount] = React.useState(counter); const handleClick = () => { setCount(count+1); } return ( <div> <p>Counter: {count}</p> <button onClick={handleClick}>Increment</button> <div> {children} </div> </div> ); } export default MyCard;
- Create a new file called
MyCard.test.js
in the same folder asMyCard.js
with the following content:
There are four separate tests here.// src/MyCard.test.js import React from "react"; import MyCard from "./MyCard"; import { shallow } from "enzyme"; describe("<MyCard />", () => { // Test #1 it("renders without crashing", () => { shallow(<MyCard />); }); // Test #2 it("renders counter correctly", () => { const wrapper = shallow( <MyCard counter={0} /> ); expect(wrapper.find("p").text()).toEqual("Counter: 0"); }); // Test #3 it("renders children when passed in", () => { const wrapper = shallow(( <MyCard> <p>Hi I am a child component</p> </MyCard> )); expect(wrapper.contains(<p>Hi I am a child component</p>)).toEqual(true); }); // Test #4 it("simulates click events", () => { const wrapper = shallow(( <MyCard counter={0} /> )); wrapper.find("button").simulate("click"); expect(wrapper.find("p").text()).toEqual("Counter: 1"); }); });
The first one is quite similar to smoke testing. The second and third tests make sure that the rendering works as intended. And finally, the fourth test simulates a clicking event of the increment button. - To run the tests, simply run the following command in the project's root folder:
$ npm test // or $ npm test -- --coverage
That's it for shallow rendering test!