Jestでthrowされたエラーをテストしたく調べたのでメモ
これがドキュメントにあった使い方
rejectされたpromiseの理由を取り出すには .rejectsを使用する
// .rejectsを使う it('tests error with rejects', () => { expect.assertions(1); return expect(user.getUserName(3)).rejects.toEqual({ error: 'User with 3 not found.', }); }); // async/awaitを使う方法もある it('tests error with async/await and rejects', async () => { expect.assertions(1); await expect(user.getUserName(3)).rejects.toEqual({ error: 'User with 3 not found.', }); });
toEqual
を使っているが、Errorを継承したカスタムエラークラスにマッチするかをテストしたい
カスタムエラーについて
【システム開発】JavaScriptのError を拡張する - UGA Boxxx
この場合は、.rejects.toEqual
の代わりに.rejects.toThrowError
を使うのが良さそう
jestjs.io
こんな感じでテストできた
test("対応していない通貨", async () => { await expect(sut.findByCurrency("aaa")).rejects.toThrowError( new CustomError("対応していない通貨です。"), ); });