Table of contents
1.
Introduction
2.
React Hooks
3.
ReactTestUtils.act()
3.1.
Syntax
3.2.
Example
4.
FAQs
5.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

React Hooks Support

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

One of the most essential parts of React is React hooks. React hooks are essentially methods that allow us to use states without the need to write a class in React. Thus, being one of the most used features, it is something that needs to be extensively tested in order to make sure that the states don’t break during production.

This is where Enzyme comes in. The Enzyme, a Javascript Testing Utility that we will be using along with Jest in this blog, makes it easier to traverse, assert and manipulate React Components’ output. In this blog, we will learn how we can use this utility to test react hooks and state management.

React Hooks

Hooks were first introduced in React version 16.8 and since then have been a lifesaver when creating and maintaining states. It allows us to skip writing classes and still use features like using a state. Hooks are the functions that "hook into" React state and lifecycle features from function components. It does not work inside classes.Hooks are backward-compatible, which means it does not contain any breaking changes. In addition, hooks do not replace React knowledge.

ReactTestUtils.act()

The main problem with testing react hooks is that we are not able to run our test similar to how React works in the browser. Thus, here we need to use act() that helps us to run our tests similar to a React app. A common syntax of using this is:

Syntax

const wrapper = mount(<SomeComponent />);
act(() => wrapper.prop('handler')());
wrapper.update();
expect(/* ... */);
You can also try this code with Online Javascript Compiler
Run Code

However we can not wrap the result of prop() in act() as it will manipulate the final equality but we can use invoke() to simplify the code.

const wrapper = mount(<SomeComponent />);
wrapper.invoke('handler')();
expect(/* ... */);
You can also try this code with Online Javascript Compiler
Run Code

Here, invoke() invokes a function prop that was not possible before in act().

Example

First, we need to create a component with a React hook that we need to test.

const apiKey = process.env.REACT_APP_APIKEY
export const fetchData = async () => {
      const loc = e.target.elements.loc.value;
const response = await axios.get('https://api.openweathermap.org/data/2.5/weather?q=${loc}&appid=${apiKey}
')
return response.data;
}

export const Testcomp = (props) => {
    const [data, setData] = React.useState([]);
    React.useEffect(() => {
      const tempdata = await fetchData();
      setData(tempdata);
    }, []);

return (
    <>
      <div className=”data”>{data}<div/>
    </>
)
You can also try this code with Online Javascript Compiler
Run Code

Now we simply need to create a test suite to test the functionality in which the data fetched and updated using the hooks.

describe('Weather data fetched', () => {
Let container;
const wrapper = shallow(<div><Testcomp {...props}><div/>;
beforeAll(() => {
requests.fetchData;
});
beforeEach(() => {
Container = wrapper.find('Testprop').dive();
      });
it('should fetch the data', async () => {
             expect(container.find('data')).toHaveLength(1);
      });
});
You can also try this code with Online Javascript Compiler
Run Code

FAQs

1. What is the use of Enzyme Adapter?

Ans: The adapter is what helps us in having the same enzyme code irrespective of the React version in use.
 

2. Difference between Jest and Enzyme.

Ans: Enzyme only renders the parent component ignoring any child component. This is a useful restriction that ensures that we aren't rendering unnecessary components. In Jest however, we need to have the whole component rendered and stored as a snapshot.

 

3. What are all the react hooks that can be tested using Enzyme?

Ans: Though we can test all the react hooks, it is important to know that we cannot test UseEffect using shallow.
 

4. Is there anyway to test React Hooks other than Enzyme?

Ans: As Hooks are a part specific to React, it can also be tested using react-testing-library.

Key Takeaways

In this blog, we discussed how we can test react hooks using enzyme and thus are able to test one of the most important of any React App.

You may want to learn more about shallowWrapper API reference here.

Learning never stops, and to feed your quest to learn and become more skilled, head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Learning!

Live masterclass