【问题标题】:Jest finishing async test before done()开玩笑在 done() 之前完成异步测试
【发布时间】: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


【解决方案1】:

这只是关于 Jest 如何在异步测试中输出内容。我刚刚检查过,但不知道如何证明这一点。

如果您删除 done(); 呼叫,您将因为超时而失败。 如果您将期望更改为无效,您的测试也会失败。 所以它工作正常。肯定的。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2019-06-30
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多