Categories
JavaScript Answers

How to fix mockImplementation() not working in Jest?

Spread the love

Sometimes, we want to fix mockImplementation() not working in Jest.

In this article, we’ll look at how to fix mockImplementation() not working in Jest.

How to fix mockImplementation() not working in Jest?

To fix mockImplementation() not working in Jest, we should call jest.mock with a function that returns an object with the mocks.

For instance, we write

import service from './Service';

jest.mock('./Service', () => jest.fn());

to mock the ./Service module with whatever is returned by jest.fn.

Then we can mock the functions exported in ./Service with

service.func = jest.fn(() => { /*your mock*/ })

We call jest.fn with a function that mocks the implementation of the func function in from service.

Conclusion

To fix mockImplementation() not working in Jest, we should call jest.mock with a function that returns an object with the mocks.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *