Website Development

Test Cases of HOCs containing Query Component using Jest

There are a plethora of articles on testing of react components using Jest and Enzymes, but there are fewer in which they talk about testing of complex components. However, this article will help you to walk-through the testing of complex components i.e HOC containing Query components.

The main focus of this article is to reach to the component on which we are able to find wrapper of that component using Jest

Let’s take an example of the HOC with a basic query, which returns a new component:

Here we have passed Wrapped Component as an argument and when data is loaded HOC renders this passed component with new data and when loading is true it renders div component Loading… text, and if there is an error it renders div component Error text.


To test our HOCs I will be using Enzyme and Jest, you can easily add these to your project by npm or yarn task runner.

Click Here to know more

In withQueryDog.test.js, we have 3 test cases, loading, error and return a Component with new props. To check these test cases, we have used mount WithQueryHOC (loaded before each test with some mocked component) and we have used MockedProvider to mock (this allows the tests to be run in isolation and provides consistent results on every run by removing the dependence on remote data)

You may notice the prop being passed to the MockedProvider called addTypename, Reason this is here is because of how Apollo Client normally works. When a request is made with Apollo Client normally, it adds a  __typename field to every object type requested. This is to make sure that Apollo Client’s cache knows how to normalize and store the response.

When we’re making our mocks, though, we’re importing the raw queries without type names from the component files.You may also notice the await wait(0) line, it delays until the next “tick” of the event loop and allows time for that Promise returned from MockedProvider to be fulfilled. After that Promise resolves (or rejects), the component can be checked to ensure it displays the correct information.

About Author

Sagun Saluja is a technology enthusiast with 3+ years of experience working on  JavaScript projects using technologies such as ReactJS, Apollo Graphql, NodeJS, Express, Mongo, Jest.


Successive Advantage

We design solutions that bring unmatchable customer experience to life and help companies accelerate their growth agendas with breakthrough innovation.

Connect with us ➔
pattern icon