Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock.mockImplementation() not working

Tags:

jestjs

I have a service class

Service.js

class Service { } export default new Service(); 

And I am 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'm not able to access any variables declared outside of the mock, which is a bit limiting as I'd like to reconfigure what the mock returns, etc.

I tried this (inspired by this other StackOverflow article: Service mocked with Jest causes "The module factory of jest.mock() is not allowed to reference any out-of-scope variables" error)

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

Unfortunately when I am trying to run this, I get the below error:

TypeError: _Service2.default.mockImplementation is not a function 
like image 382
Janos Avatar asked Aug 19 '17 13:08

Janos


People also ask

What is mockImplementation in jest?

mockImplementation(fn) ​ Accepts a function that should be used as the implementation of the mock. The mock itself will still record all calls that go into and instances that come from itself – the only difference is that the implementation will also be executed when the mock is called. tip. jest.

What is jest fn()?

The jest. fn method allows us to create a new mock function directly. If you are mocking an object method, you can use jest.

How do you reset mock jest?

afterEach(() => { jest. clearAllMocks(); }); to call jest. clearAllMocks to clear all mocks after each test.


2 Answers

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

  1. If you need to mock only a function from 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 mock the entire Module:

    Say your service.js is in javascript/utils, create a javascript/utils/_mocks_ and inside it create a service.js file, you can then mock the entire class in this file, eg:

    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 the mockfile will be then hit through your test file execution.

like image 100
guillaume Avatar answered Sep 24 '22 10:09

guillaume


The mock is equal to jest.fn. You need to call jest.fn to create a mocked function.

So this:

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

Should be:

jest.mock('./Service', () => jest.fn()); 
like image 34
deleteme Avatar answered Sep 25 '22 10:09

deleteme