Jest Mock with Real Modules

Mocking with jest.requireActual

Image for post
Image for post
Photo by Alice Pasqual on Unsplash

Not long ago when I reviewed PR, I found an interesting use case with Jest mock, and would like to share with you.

So most of the time when we used a 3rd party module in the code, we can just mock the whole module. But there are times when we need to use parts of the real implementation of the module, this is when jest.requireActual comes handy.

Consider a module like below:

And then we have a function that we want to be tested:

Finally this is how we test it :

Notice when we do the following, we are returning { trackEventName, trackEvent } and then trackEvent: jest.fn() overwrite the trackeEvent returned from the module.

The reason we want to do this is because when we do the mounting:

There is this method get triggered inside the component:

We still want to call trackEventName but just want to mock trackEvent . So we require the real module thereby requiring the real trackEventName and overwrite the latter with the mocked trackEvent .

Of course you can mock trackEventName as well. But in this test, we don’t want to add another layer of complexity, and would like to actually test if the trackEventName can be passed in to trackEvent and rendered by ClickBoxWithTracking .

You can even more explicitly requiring the real trackEventName like this after you require the module.

You can learn more about jest.requireActual in the documentation.

Happy reading!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store