我正在尝试向我正在开发的 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 */
最佳答案
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 tonode_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 calljest.mock('module_name')
.
关于javascript - 使用 __mocks__ 的手动模拟不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55571012/