【发布时间】:2022-10-21 07:18:58
【问题描述】:
我正在尝试使用 Jest 测试 nodejs 函数。我是 Jest 的初学者,所以我认为这是我构建测试的方式中的一个问题。
当手动或从应用程序中调用时,该函数可以正常工作。但是当从 Jest 测试中调用时,它要么超时,要么返回一个空对象,要么跌倒。
要测试的功能:
async function createUser(username, password){
try{
const user = await UserModel.create({ username, password });
return true;
} catch(error){
if(error.code == 11000){
const field = Object.keys(error.keyValue);
const err = Error("Account with username " + field + " already exists");
throw err;
}
if(error.name == 'ValidationError'){
const err = Error("Error creating new user");
throw err;
}
const err = Error("Unknown error creating new user");
throw err;
}
}
和我创建的 Jest 测试:
test('createUser: Non empty input should create account and return true', async () => {
const data = await register.createUser('johnsmith1', 'smithjohn');
expect(data).toBe(true);
});
test('createUser: Duplicate user/pass should not create user and should throw error', async () => {
try{
await register.createUser('johnsmith1', 'smithjohn');
} catch(error){
expect(error).toMatch('error');
}
});
当运行两个测试超时:
createUser: Duplicate user/pass should not create user and should throw error
thrown: "Exceeded timeout of 5000 ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
74 | });
75 |
> 76 | test('createUser: Duplicate user/pass should not create user and should throw error', async () => {
| ^
77 | try{
78 | await register.createUser('johnsmith1', 'smithjohn');
79 | } catch(error){
at Object.test (tests/register.test.js:76:1)
【问题讨论】:
标签: node.js mongodb express jestjs