LoginSignup
5
6

More than 5 years have passed since last update.

[Jest] Promiseの中でthrowされたエラーをテストする方法

Posted at

はじめに

Jestでエラー処理をテストするときによくやるやつ。
Promise中にエラーを投げる例外処理があるとして、それをテストするやり方。
いつもうろ覚え状態なので書いておく。

やり方

ここに載ってる。
https://jestjs.io/docs/en/tutorial-async#rejects

こんなPromiseの処理があるとして、

PromiseFunc.ts
export default class PromiseFunc {
  constructor() {}
  public async helloAsync(name) {
    if(!name) throw new Error('name is empty');
    return new Promise((resolve) => {
      resolve('Hello ' + name);
    });
  }
}

こんな風に使ってるとする。

Hello.ts
import promiseFunc from './PromiseFunc';

const main = async () => {
  try {
    const func = new promiseFunc();
    const res = await func.helloAsync('bathtimefish');
    console.log(res);
  } catch(e) {
    console.error(e);
  }
};

main();

PromiseFunc.test.tsのテストはこんな感じ。

PromiseFunc.test.ts
import promiseFunc from '../PromiseFunc';

describe('PromiseFunc', () {

  it('should get greeting', async () => {
    const func = new promiseFunc();
    const res = await func.helloAsync('bathtimefish');
    expect(res).toBe('Hello bathtimefish');
    // await (expect(func.helloAsync('bathtimefish'))).resolves.toEqual('Hello bathtimefish');
  });

  it('should throw error because of name is empty', async () => {
    const func = new promiseFunc();
    await expect(func.helloAsync(null)).rejects.toEqual(new Error('name is empty'));
  });

});

rejects 便利。正常系のテストも上記でコメントしてるようにresolveを使う手があるんだけど、個人的にはtoBeのほうが平滑な感じがして好き。

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6