Jest Mocking Cheatsheet

Matti Bar-Zeev - Feb 25 '22 - - Dev Community

Here are a few useful Jest mocking snippets which help me get through the day.

I bet you’re all like me when it comes to Jest mocking - you don’t remember how exactly it should be done for a specific use case and how the syntax is supposed to be.
No shame in that, but I recently got a little tired of it so I decided to take action and save myself some time by having a Cheatsheet where I will put all these elusive mock code snippets.
I hope you will find them useful as well.

Mocks play a crucial part in testing Allowing to fixate a state in which the test runs in and clear out any noise which is not relevant to the test at hand.
It is also good to mention that over-mocking is considered a code-smell which indicates a failure in design and overly coupled architecture, so be careful with that axe, Eugene 😉

Disclaimer: Jest has more than a few ways to mock modules and methods. These are my own choices. If you feel that there are better ways of achieving these mocks, please share them with us in the comments below, so that we can all learn.



Mock a React Component

jest.mock('./MyComponent', () => (props)=><div>MyComponentMock</div>);
Enter fullscreen mode Exit fullscreen mode

Sometimes you have no interest in rendering the origin nested component that your component is using. The reason can be that you don’t want to take care of mocking inner dependencies or you really don’t care about the inner component. In this case it might be a good idea to just mock the component.
As you can see the mock method receives the props though I don’t use them, but if you really like to you can render these props for assertions or what have you.

Mock a single (or several) method of a module

jest.mock('react-dom', ()=>({
   ...jest.requireActual('react-dom'),
   createPortal: (Component)=>Component
}))
Enter fullscreen mode Exit fullscreen mode

Sometimes you would like to mock specific methods of a module (it can be a 3rd party or your own), like in the case above -
Here we are mocking react-dom’s createPortal to avoid errors such as Target container is not a DOM element. All the other implementations are kept intact as in the origin module. The order, obviously, has meaning here.

Mock global objects methods e.g. Math, Date

jest.spyOn(Math, 'random').mockReturnValue(0.123456789);

jest.spyOn(Date, 'now').mockReturnValue('123456789');
Enter fullscreen mode Exit fullscreen mode

There are situations where you code is using Math.random (or any other Math method), you cannot count on its value and you need to fix the value. Same goes for the Date object and others.
(BTW, avoid mocking console methods - your source code should not have them at all).

Mock a React Hook

jest.mock('@pedalboard/hooks', () => ({
   usePagination: () => ({
       cursor: 5,
       totalPages: 10,
       goPrev: jest.fn(),
       goNext: jest.fn(),
   }),
}));
Enter fullscreen mode Exit fullscreen mode

Sometimes our components rely on hooks logic and in order for us to test these components well, we need to mock these hooks.
Here I mocked a hook which from my hooks package @pedalboard/hooks and imported into a component like so:

import {usePagination} from '@pedalboard/hooks';
Enter fullscreen mode Exit fullscreen mode

This hook returns some values and 2 methods. Since the example above is using jest.mock it is declared once and applies throughout the entire tests.

If I want to make it for a single test, here is how I go about it:

import * as hooks from '@pedalboard/hooks';
... 
jest.spyOn(hooks, 'usePagination').mockReturnValue({
           cursor: 1,
           totalPages: 20,
           goPrev: jest.fn(),
           goNext: jest.fn(),
       });
Enter fullscreen mode Exit fullscreen mode

To be continued…

This is not a complete list of Jest mocks cheats. I plan to add more as I bump into them along the way, so I recommend keeping this one bookmarked, just in case ;)

As always if you have other suggestions or additional mock snippets you know to be useful, please share them with us!

Hey! If you liked what you've just read check out @mattibarzeev on Twitter 🍻

Photo by Sigmund on Unsplash

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player