How to Mock Using Jest.spyOn (Part 2)

Photo by Bing Han on Unsplash

This is part 2 of my JavaScript testing series. You can check out How to Write Functional Tests in React (Part 1) here!

Mocking is an important concept in testing where a subject that is dependent on data has said data replaced so that it can be controlled and measured.

There are a handful of ways you can mock in Jest. You can mock a function with or mock a module with , but my preferred method of mocking is by using .

Tracking Calls

allows you to mock either the whole module or the individual functions of the module. At its most general usage, it can be used to track calls on a method:

Any call to , either in this test file or (if the function is being called as a side-effect) in some other file, will be tracked within this ) function.

Overwriting/Mocking A Function

If you want to mock out an implementation and overwrite the original function, you can chain to the end of :

In this test, we are mocking the implementation of JavaScript’s global function. We set it to return a static value of (converted to milliseconds).

On the backend, where is implemented, we use to define the field of a . When is called, will be run on the backend and will use the mocked to return the date we set (instead of the actual ).

By mocking , we can ensure that:

  1. createContract is creating Contract records with a startedOn field in the correct format
  2. our tests will pass consistently because Date.now() is returning a value that we can confirm every time

At the end of our test, we can restore the hijacked function to its original implementation with .

BONUS: before/after Hooks

We can use jest’s and hooks so that we keep our tests DRY when they have similar environments to setup:

Before every function is run in the file, jest will mock , and after every , jest will restore the function to its original implementation. Using the hooks for setup ensures that every test is fresh and independent of each other.

Note: we could probably use instead of the tests aren’t mutating the date.

I hope this article helped you understand the usage of mocks a litter better. Please don’t hesitate to reach out if you have any questions. You can drop us a line through Echobind’s contact page or just leave a comment here. I wish you the best of luck to you on your next npm run jest!

More about:

Jeffery Zhen