我在Jest写了一个异步测试但遇到了麻烦。我非常确定测试是在完成和传递之前,异步调用返回任何东西,尽管我尝试了一切。我知道该函数有效,因为它在测试套件完成后会记录正确的响应。这是测试代码:
describe('updateUser', () => {
test('should update a user', (done) => {
updateUser(user).then(({err, res}) => {
console.log('updated user:', err, res); // this show up after the test is done
expect(err).toBeFalsy();
expect(res).toBeTruthy();
done();
});
});
});
控制台输出:
updateUser
✓ should update a user (68ms)
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 6.058s
Ran all test suites.
console.log server/db/crud_Users/crud_user.test.js:38
updated user: null { homeLocations: [],
meetingPlaces: [],
hostedEvents: [],
attendingEvents: [],
flags: [],
tokens: [],
_id: 5b2147495995cb45f9c4f079,
name: 'test',
email: '83277963493533480000@test.com',
password: 'testtest',
ageRange: '1',
gender: 'Female',
accountCreatedAt: null,
__v: 0 }
预期行为:测试套件在完成之前等待console.log语句和断言运行。
实际行为:它没有。
我也试过让测试回调成为异步函数并等待updateUser
调用,但没有改变;我尝试在第二个done()
块中添加.then
回调,但没有结果。
答案 0 :(得分:1)
这只是关于Jest在异步测试中如何输出内容。我刚刚检查过,但看不到如何证明。
如果您删除done();
呼叫,则由于超时而导致测试失败。
如果您将期望更改为无效,则测试也会失败。
所以它工作正常。当然可以。
此外,由于updateUser
返回Promise,因此您无需运行done()
。只需返回Promise,这样测试就会轻松一些:
test('should update a user', () => {
return updateUser(user).then(({err, res}) => {
expect(err).toBeFalsy();
expect(res).toBeTruthy();
});
});