Jestでは
Promise(.then / .catch)
async / await
どちらもテストできます。
非同期関数は「いつ終わるかわからない」ので、
**await
や return
を使って「待つ」**ことが大事。
// 非同期で2秒後に3を返す関数
const asyncAdd = (a: number, b: number): Promise<number> =>
new Promise((resolve) => setTimeout(() => resolve(a + b), 2000));
// returnでPromiseを返して、Jestに「待て」と伝える
test('asyncAdd 1 + 2 は 3 を返す', () => {
return asyncAdd(1, 2).then((result) => {
expect(result).toBe(3);
});
});
💡 return
がないとテストが終わるのを待たずに終了してしまう。
test('asyncAdd 3 + 4 は 7 を返す(await)', async () => {
const result = await asyncAdd(3, 4);
expect(result).toBe(7);
});
💡 await
で待っている間は次の行に進まない
→ return
いらない。
// 5未満ならrejectする関数
const asyncSubtract = (a: number, b: number): Promise<number> =>
new Promise((resolve, reject) => {
const result = a - b;
if (result < 5) {
reject(new Error('result is too small'));
} else {
resolve(result);
}
});
// エラーが発生することを確認する
test('asyncSubtract 5 - 2 はエラーを投げる', async () => {
await expect(asyncSubtract(5, 2)).rejects.toThrow('result is too small');
});