私は、非同期関数が次のようにスローすることを期待する非同期テストを書いています:
it("expects to have failed", async () => {
let getBadResults = async () => {
await failingAsyncTest()
}
expect(await getBadResults()).toThrow()
})
しかし、jest はテストに合格する代わりに失敗します。
FAIL src/failing-test.spec.js
● expects to have failed
Failed: I should fail!
テストを書き直すと次のようになります。
expect(async () => {
await failingAsyncTest()
}).toThrow()
テストに合格する代わりに、次のエラーが発生します:
expect(function).toThrow(undefined)
Expected the function to throw an error.
But it didn't throw anything.
ベストアンサー1
次のようにして非同期関数をテストできます。
it('should test async errors', async () => {
await expect(failingAsyncTest())
.rejects
.toThrow('I should fail');
});
「失敗するはずです」という文字列は、スローされたエラーの任意の部分と一致します。