0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Jest useFakeTimers] setTimeout+Promiseをテストする

Posted at

あれは遥か太古、時間にすればおよそ数時間前のこと。

私は宗教上の理由でsetTimeoutとpromiseを組み合わせて使う事になったのだが、テストがうまく書けなくて詰んでいた。

まさかJestに問題があるとは思わず、自分のコードの粗探しを必死に行ったものの、見つからないどころか画面で確認したら正しく動いていた。

ググってみるとこんなIssueが見つかり、一度は諦めたが、テストが書けないのがツラすぎて再挑戦した。

そしてStack Overflowにて神を見た。

神は「await Promise.resolve();あれ」と言われた。すると動いた。

jest.useFakeTimers();

describe('FakeTimers with Promise', () => {
  it('does not work', () => {
    let called1 = false;
    let called2 = false;
    setTimeout(async () => {
      called1 = true;
      await Promise.resolve();
      called2 = true;
    }, 0);

    jest.runAllTimers();

    // なんと、called1しかtrueではない。
    expect(called1).toBeTruthy();
    expect(called2).toBeFalsy();
  });

  it('will work', async () => {
    let called1 = false;
    let called2 = false;
    setTimeout(async () => {
      called1 = true;
      await Promise.resolve();
      called2 = true;
    }, 0);

    jest.runAllTimers();

    // ここが味噌。
    await Promise.resolve();

    // どちらもtrueになっている。
    expect(called1).toBeTruthy();
    expect(called2).toBeTruthy();
  });
});

あーめn

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?