javascript - 使用 __mocks__ 的手动模拟不起作用

标签 javascript node.js jes

我正在尝试向我正在开发的 Node 应用程序添加一些测试。我浏览了手动模拟的笑话文档,并尝试按照指示创建 mocks 文件夹。请在下面找到文件夹结构。

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

如您所见,我尝试模拟两个模块,fb.js(用户模块)和 firebase-admin.js(node_modules 模块)。 firebase-admin.js 模拟工作没有任何问题。但是用户模块 mock 甚至没有被 jest 接受。实际的 fb.js 模块一直在被调用。

我已经尝试在我的项目中为各种用户模块创建mocks 目录,但没有一个被选中。我缺少任何额外的配置吗??。目前我正在通过仅模拟 firebase-admin Node 模块来解决这个问题。但是我想模拟用户模块而不是 firebase-admin 模块,这样我的 firebase 配置也会被模拟。如果需要更多信息,请告诉我。

__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);
  });
});

应用程序/解析器/mutation.js

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

/* other app code here */

最佳答案

来自 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').

关于javascript - 使用 __mocks__ 的手动模拟不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55571012/

相关文章:

java - 将 Jython/JES 生成的影片保存在本地磁盘上

javascript - 无法在 jquery 中获取 Ajax CORS 请求

javascript - NodeJS/jQuery - 投票通知 API

javascript - Jquery Mobile 不透明度不起作用 :(

node.js - MySQL knex 数学运算

node.js - Instagram API : SyntaxError: Unexpected token <

python - 裁剪功能 Jython JES

python - 在 Jython/Python 中创建电影

javascript - 如果其中一个 <li> 更改位置,则立即在多个 <ul> 中移动列表元素顺序

javascript - Javascript 中的正则表达式组