0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

単体試験Tips(JEST)

0
Last updated at Posted at 2025-08-27

単体試験Tips(JEST)

単体試験をしていてベストプラクティスと言われていたが、ちゃんと理解していなかったので復習
いろいろやっていると忘れるので、定期的な復習が大事と実感・・・

  • jsdom(jestによる仮想DOM)は非同期的に更新される
  • そのため、そのあとに同期的にexpectをしても、タイミング的にFailになる
  • JSでの非同期処理はイベントループという1本のスレッドで実施される
  • そのため、expectもPromiseを使用して空の非同期処理を実行し、イベントループにのせる。そして、thenの中でexpectすれば、jsdom更新後にテストできるので問題なくなる
return Promise.resolve().then(() => { // thenで非同期処理なし
      expect(div.textContent).toBe('テストしたい内容'); // この処理をイベントループのスレッドにのせることが目的
    });
0
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?