【发布时间】:2021-10-20 04:27:08
【问题描述】:
我是使用 Jest 进行单元测试的新手。 这是我的 Account 类
....
const Account = mongoose.model('Account', AccountSchema);
module.exports = {
Account,
};
这是我的帐户服务
function createAccount(data) {
const account = new Account(user_id: data.user_id);
}
这是我的 accountService.test
const { createAccount } = require('../../src/service/accountService')
const { Account } = require('../../src/models/Account');
jest.mock('../../src/models/Account', () => ({
Account: {
create: jest.fn(),
findOne: jest.fn(),
find: jest.fn(),
}
}));
describe('Test function', () => {
it('Run create account function', async () => {
const result = await createAccount({
user_id: 1,
});
expect(result).toEqual('');
});
});
但是当我运行它时,会出现错误
TypeError: Account is not a constructor
请教我如何修复它以及如何模拟帐户?感谢您的关注。
【问题讨论】:
-
Account不是构造函数,它只是一个对象。您的测试替身需要与他们要替换的东西具有相同的界面 - 您可以使用例如返回对象的函数(不是箭头函数)。
标签: javascript node.js unit-testing mongoose jestjs