最常见的异步模式是回调函数。

例如,假设您有一个 函数,获取一些数据并在完成时调用 callback(data)。 You want to test that this returned data is the string 'peanut butter'.

默认情况下,Jest 测试一旦执行到末尾就会完成。 那意味着该测试将不会按预期工作:

问题在于一旦fetchData执行结束,此测试就在没有调用回调函数前结束。

还有另一种形式的 test,解决此问题。 使用单个参数调用 done,而不是将测试放在一个空参数的函数。 Jest会等done回调函数执行结束后,结束测试。

  1. test('the data is peanut butter', done => {
  2. function callback(data) {
  3. try {
  4. expect(data).toBe('peanut butter');
  5. done();
  6. } catch (error) {
  7. }
  8. }
  9. fetchData(callback);
  10. });

In case expect statement fails it throws an error and is not called. If we want to see in the test log why it failed, we have to wrap expect in try block and pass error in catch block to done. Otherwise, we end up with opaque timeout error and no knowledge of what value was received by expect(data).

If your code uses promises, there is a more straightforward way to handle asynchronous tests. Return a promise from your test, and Jest will wait for that promise to resolve. 如果承诺被拒绝,则测试将自动失败。

举个例子,如果 fetchData 不使用回调函数,而是返回一个 Promise,其解析值为字符串 'peanut butter' 我们可以这样测试:

一定不要忘记把 promise 作为返回值⸺如果你忘了 return 语句的话,在 fetchData 返回的这个 promise 被 resolve、then() 有机会执行之前,测试就已经被视为已经完成了。

如果你想要 Promise 被拒绝,使用 .catch 方法。 请确保添加 expect.assertions 来验证一定数量的断言被调用。 否则一个fulfilled态的 Promise 不会让测试失败︰

  1. test('the fetch fails with an error', () => {
  2. expect.assertions(1);
  3. return fetchData().catch(e => expect(e).toMatch('error'));
  4. });

一定不要忘记把整个断言作为返回值返回⸺如果你忘了return语句的话,在 fetchData 返回的这个 promise 变更为 resolved 状态、then() 有机会执行之前,测试就已经被视为已经完成了。

如果你想要 Promise 被拒绝,使用 .catch 方法。 它参照工程 .resolves 匹配器。 如果 Promise 被拒绝,则测试将自动失败。

  1. return expect(fetchData()).rejects.toMatch('error');
  2. });

或者,您可以在测试中使用 asyncawait。 To write an async test, use the async keyword in front of the function passed to test. 例如,可以用来测试相同的 fetchData 方案︰

You can combine async and await with .resolves or .rejects.

  1. test('the data is peanut butter', async () => {
  2. await expect(fetchData()).resolves.toBe('peanut butter');
  3. });
  4. test('the fetch fails with an error', async () => {
  5. await expect(fetchData()).rejects.toThrow('error');
  6. });

In these cases, async and await are effectively syntactic sugar for the same logic as the promises example uses.