Mock Function using Jest

Brian Yudiva
3 min readMay 2, 2021
Photo by Kate Trysh on Unsplash

Why do I need to mock our API call? Hmm well let’s see some scenarios

  • the API is down — how do you test your code if the API itself is down
  • the API is changed — you know that your code should work, but you don’t know that just now the API just changed is return call. Then, you must change your code to pass the test
  • you gave up — skipping the API call function test and don’t care if the coverage falls down

Well actually, your task is to process the returned API call. And no, no, you should not test your API return call, that should be the API developers job.

That’s why you need to mock API calls. This way, your code test will passed even if the API is down and if there’s changes to the API, you can refactor it.

Mocking

Mocking is a way to mock function on a test, and to imitate the high coupled function, for example API or a component that use function as a parameter. In TDD, a test should be focused on testing one function test. So we don’t to test other function output on a function test.

Let’s say there’s function A and B. Function A need to be tested and it’s calling Function B. Assume Function B is on another service and it’s already passed the test. From that, then you don’t need to retest Function B and it will be difficult to call Function B because its on another service and the service need to restarted.

To handle that issue, we need to mock Function B. We can mock Function B to mock the given return output. So, we can focus on testing Function A without worrying about Function B because it’s already mocked.

Jest Mock

Mock Function

In our PPL project, we use mock function to use it as a parameter for the Filter component.

our test code

We mock handleFilterValue() function using jest.fn()so we can pass it as a parameter for <DateModifiedFilter/>component, because handleFilterValue() function is from its parent component. This way, we can get 100% coverage for this component because we don’t need to retest the handleFilterValue() function.

Mock API

We mock JavaScript fetch to imitate and return the mocked output.

our test code

Before mocking, we make an Promise output because the function is async, then we pass the output to the jest.fn()using mockImplementation()to return the output when fetch called. This way, we can ensured that the output will be the same for all test.

Then we make the test itself async and using waitFor()function to wait the mocked function return its output, because the function fetch using async. After each test, we reset the mock to make sure each test have new mocked API call.

That’s all I have for Mock, make sure to read my recent articles.

To sum up, we use Mock to prevent API call in testing and false negative test. Also, mock can make the test will be faster and more robust.

--

--