Manual mocking using __mocks__ not working

Suneeth Lenin picture Suneeth Lenin · Apr 8, 2019 · Viewed 9.1k times · Source

I'm trying to add some tests to the node application I'm developing. I went through jest documentation for manual mocking and tried creating mocks folder as instructed. Please find the folder structure below.

app
 - firebase
  - fb.js
  - __mocks__
    - fb.js
    - firebase-admin.js
 - resolvers
    - mutation.js
__tests__
 - user.spec.js

As you can see, I have tried to mock two modules, fb.js (user module) and firebase-admin.js (node_modules module). firebase-admin.js mocking works without any problem. But user module mock is not even getting picked up by jest. The actual fb.js module is getting invoked all the time.

I have tried creating mocks directory for various user modules in my project but none of it is getting picked up. Is there any extra configuration I'm missing ??. currently I'm working around this problem by mocking firebase-admin node module only. But I want to mock the user module instead of firebase-admin module so that my firebase configurations are also mocked. Please let me know if any more information is needed.

__mocks__/fb.js

module.exports = {
   auth: jest.fn(() => "testing")
};

__mocks__/fb-admin.js

module.exports = {};

__tests__/user.spec.js

const request = require('supertest');
const server = require('../app').createHttpServer({});

const app = request(server);

describe('login resolvers', () => {
  test('should sign up user', async () => {
    const response = await app.post('/')
      .send({
        query: `mutation {
          signUp(idToken: "esd45sdfd...") {
            user {
              id
              locked
              revoked
            }
          }
        }
        `,
      })
      .set('Accept', 'application/json')
      .expect(200);
    console.log(response.text);
  });
});

app/resolvers/mutation.js

const admin = require('../firebase/fb');

/* other app code here */

Answer

user487779 picture user487779 · Apr 11, 2019

From the docs on Manual Mocks:

When we require that module in our tests, then explicitly calling jest.mock('./moduleName') is required.

If the module you are mocking is a Node module (e.g.: lodash), the mock should be placed in the __mocks__ directory adjacent to node_modules (unless you configured roots to point to a folder other than the project root) and will be automatically mocked. There's no need to explicitly call jest.mock('module_name').