すべてが同期して実行されるわけではないため、すべてが同期的にテストされる必要はありません。 Jestは、非同期テストのためのいくつかのオプションを提供します。

コールバックの使用

関数がパラメーターを受け入れる場合、Jestはそれにdoneコールバックを与えます。 テストは、doneまたはdone.failが呼び出されるか、タイムアウトになるまで実行されます。 これは、オブザーバブルのテストに役立ちます。

// Let's say you're testing a cup that emits an event when it is full or spills.
it('fills without spilling.', (done) => {
  const smartCup = new SmartCup();
  // The event happened, so call `done`.
  smartCup.on('full', () => done());
  // If a failing condition happens, you can call `done.fail`.
  smartCup.on('spilled', () => done.fail());
  smartCup.fill();
});

関数がパラメーターを受け入れる場合、Jestはdoneを待ちます。 だから次のようなもの:

it('works synchronously.', (done) => {
  expect(1).toBeGreaterThan(0);
});

doneが呼び出されることはないため、タイムアウトになるまで実行されます。

約束を返す

promiseを返すことにより、テストを非同期にすることもできます。

it('returns a number.', () => {
  return getId()
    // After `getId` resolves, you can test it against your expectations.
    .then(id => expect(typeof id).toEqual('number'));
});

非同期関数はpromiseを返すので、それらも使用できます。

// Same as above.
it('returns a number.', async () => {
  const id = await getId()
  expect(typeof id).toEqual('number');
});