In this article we will focus on Jest Mock Function utility. Let’s walk through to one of the most useful unit test functions. But before we do so, if this is your first time with Jest and Enzyme, we suggest you start by reading our previous article “Testing a React web app using Jest and Enzyme” and then come back to this one.
Why would we need a Jest Mock Function? How do we define it?
When we are developing on React it’s very common to have components that are part of other components, and each component has its own props. Let’s imagine that we have a main component which has a child component and we want to create unit tests for the main one. One of our tests should check that the child component exists and has appropriate props. To do that, we will need to mock the child component using jest.mock and then we can access the component as if we were instantiating it using the shallow function. Once we define the mock constructor, checking the props is very simple.
Let’s review how it works with an example:
Easy, right? But you are probably asking yourself ‘what about the onSubmit function?’ We should check that it is a function and that’s it? Well, if you are asking yourself that, you are thinking like a true unit tester. The answer is simple, it depends on what you need; in some cases it could be enough and in others, it could not. Let’s imagine a scenario where, given the function inputs, you need to simulate a response.
How can we mock a function?
Basically, we need to create a spy function that will trigger the simulated response. To do that, we use jest.fn – from Jest. Once we have the spy, we can test the feature using toHaveBeenCalled or toHaveBeenCalledWith – also from Jest – to check if the spy was called or not. Others useful functions could be simulate – from Enzyme – to simulate triggering an event in case we need it, and mockReturnValue – from Jest – to simulate the response in case we want to test something with that specific value.
Let’s wrap up our idea by creating the “ChildComponent” test:
Jest Mock Function conclusion
The Jest Mock Function is a simple but powerful unit test tool that any developer must know. There are a couple more utilities for mocks, so we recommend you continue reading about this and putting it into practice on your own codes.
We hope you find this article useful, and if you have more questions about it, you can visit Jest’s official documentation.