简体   繁体   中英

Manual mocking using __mocks__ not working

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 */

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 (eg: 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') .

I had to read the documentation very carefully. Especially the part about "unless you configured roots to point to a folder other than the project root" . Double-check that you set up the __mocks__ folder in the source folder you specified for Jest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM