【发布时间】:2018-11-23 08:14:07
【问题描述】:
我正在用 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 调用,但没有任何改变;我也尝试在第二个 .then 块中添加 done() 回调,但没有任何结果。
【问题讨论】:
-
Jest 捕获标准输出并且直到最后才渲染它。见this issue。否则您的测试是正确的,这是正常行为。
标签: asynchronous testing jestjs