在调用 done() 之前完成 Jest 异步测试

3

我正在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 捕获 stdout 并在结束前不会呈现它。请参见此问题。否则,您的测试是正确的,这是正常行为。 - ggorlen
1个回答

2

这个问题涉及Jest在异步测试中输出的内容。我刚刚检查了一下,但是没有看到如何证明。

如果你删除 done(); 调用,你会因为超时而导致测试失败。如果你将你的期望值改为无效值,你也会使测试失败。所以它运行得很好。当然。

此外,由于 updateUser 返回 Promise,所以你不需要运行 done()。只需返回 Promise,这样测试就会稍微轻一些:

test('should update a user', () => {
  return updateUser(user).then(({err, res}) => {
    expect(err).toBeFalsy();
    expect(res).toBeTruthy();
  });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接