Jest Mocking Cheatsheet
Tags: javascript, webdev, testing, beginners
Published: 2022-02-25 07:46:32

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 :wink:

> 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](#snippet-1)
* [Mock a single (or several) method of a module](#snippet-2)
* [Mock global objects methods e.g. Math, Date](#snippet-3)
* [Mock a React Hook](#snippet-4)

***

## <a name="snippet-1"></a>Mock a React Component 

```javascript 
jest.mock('./MyComponent', () => (props)=><div>MyComponentMock</div>);
``` 

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. 

## <a name="snippet-2"></a>Mock a single (or several) method of a module 

```javascript 
jest.mock('react-dom', ()=>({
   ...jest.requireActual('react-dom'),
   createPortal: (Component)=>Component
}))
```

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.

## <a name="snippet-3"></a>Mock global objects methods e.g. Math, Date 

```javascript 
jest.spyOn(Math, 'random').mockReturnValue(0.123456789);
       
jest.spyOn(Date, 'now').mockReturnValue('123456789');
``` 
 
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).

## <a name="snippet-4"></a>Mock a React Hook

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

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:

```javascript
import {usePagination} from '@pedalboard/hooks';
```

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:

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

## 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 <a href="https://twitter.com/mattibarzeev?ref_src=twsrc%5Etfw" class="twitter-follow-button" data-show-count="false">@mattibarzeev</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> on Twitter* :beers:

<small><small><small>Photo by <a href="https://unsplash.com/@sigmund?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Sigmund</a> on <a href="https://unsplash.com/s/photos/crafts?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a></small></small></small>