【发布时间】:2020-07-27 15:12:36
【问题描述】:
我在使用 commonjs 模拟我的模块中的特定函数时遇到问题
示例模块db.js
function createDefaultProfile(user_id) {
return { version: 1, username: user_id };
}
function updateOrCreateProfile(user_id, profile) {
if (profile && profile.credential_id) return null; //no need to update
if (!profile) profile = createDefaultProfile(user_id);
if (!profile.credential_id) {
//update profile with key
}
module.exports = {createDefaultProfile, updateOrCreateProfile }
示例测试文件尝试1:
describe("updateOrCreateUser()", () => {
const db = require('../db.js')
it("should call createDefaultProfile() when no profile is provided", () => {
db.createDefaultProfile = jest.fn()
db.updateOrCreateProfile(userID)
expect(db.createDefaultProfile).toHaveBeenCalledTimes(1)
})
})
示例测试文件尝试2:
describe("updateOrCreateUser()", () => {
jest.mock('../db', () => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual('../db');
return {
__esModule: true, // Use it when dealing with esModules
...originalModule,
createDefaultProfile: jest.fn().mockReturnValue('arbitrary value'),
}
})
const db = require('../db.js')
it("should call createDefaultProfile() when no profile is provided", () => {
db.updateOrCreateProfile(userID)
expect(db.createDefaultProfile).toHaveBeenCalledTimes(1)
})
})
两者都返回错误的值,因为模拟模块永远不会被调用.. 在这两种情况下,模拟模块的范围似乎都不正确......
【问题讨论】:
标签: javascript testing jestjs commonjs