Mock.mockImplementation () not working

I have a class of service

Service.js

class Service { } export default new Service(); 

And I'm trying to provide a mock implementation for this. If I use something like this:

 jest.mock('./Service', () => { ... my mock stuff }); 

It works fine, however I cannot access any variables declared outside the layout, which is a bit limiting, since I would like to reconfigure what mock returns, etc.

I tried this (inspired by this other StackOverflow article: Service mocking with Jest reasons "Factory module for jest.mock () is not allowed to refer to any out-of-scope")

 import service from './Service'; jest.mock('./Service', () => jest.fn); service.mockImplementation(() => { return { ... mock stuff } ); 

Unfortunately, when I try to run this, I get the following error:

 TypeError: _Service2.default.mockImplementation is not a function 
+13
jestjs
source share
3 answers

Layout equals jest.fn. You need to call jest.fn to create the mocked function.

So this is:

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

Must be:

 jest.mock('./Service', () => jest.fn()); 
+9
source share

You need to save your mocked component in a variable with a name prefixed by "mock", and make sure that you return the object with the default property when importing your service from the default into the "main.js" file.

 // Service.js class Service { } export default new Service(); // main.test.js (main.js contains "import Service from './Service';") const mockService = () => jest.fn(); jest.mock('./Service', () => { return { default: mockService } }); 
0
source share

I had the same problem as @Janos, other answers didn't help either. You could do two things:

1 / If you need to simulate only a function from the Service, in your test file:

 import service from './Service'; jest.mock('./Service', () => jest.fn()); service.yourFunction = jest.fn(() => { /*your mock*/ }) 

2 / If you need to simulate the whole module:

Let's say your service.js is located in javascript / utils, create javascript / utils / __ mocks__ and create a service.js file inside it, after which you can model the whole class in this file, for example:

 const myObj = {foo: "bar"} const myFunction1 = jest.fn(() => { return Promise.resolve(myObj) }) const myFunction2 = ... module.exports = { myFunction1, myFunction2 } 

then in your test file you just add:

 jest.mock('./javascript/utils/service') 

Functions exported from mockfile will be checked when your test file is executed.

0
source share

All Articles