3
4

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】非同期処理のテストを書こう~Promiseとasync/await~

Posted at

非同期処理のテストを書こう

Jestを使った非同期処理のテストのテストをまとめたいと思います。
プロジェクトでは、Promiseとasync/awaitを使った非同期処理を書くことが多いのでこの2点のテストコードをまとました。

Promiseのテストの書き方

  • 公式ドキュメント
  • .resolves関数を利用することでPromiseが処理され、 Promise.resolveが実行された値を評価することができます。
  • returnを省略した場合、テストはfetchDataがresolveされpromiseが返ってくる前に実行されます
assertion.test.js
const fetchData = () => Promise.resolve("hoge");

test("resolves to hoge", () => {
  return expect(fetchData()).resolves.toBe("hoge");
});

async/awaitのテストの書き方

  • 公式ドキュメント
  • 非同期テストを書くには、テストに渡す関数の前にasync キーワードを記述するだけです
assertion.test.js
const fetchData = () => Promise.resolve("hoge");

test("resolves to hoge with async/await", async () => {
  await expect(fetchData()).resolves.toBe("hoge");
});

rejectsの書き方

  • 公式ドキュメント
  • promiseがrejectされることを期待するケースでは.rejectsを使用を使用します
assertion.test.js

const fetchData = (category = "hoge") =>
  category === "hoge"
    ? Promise.resolve("hoge")
    : Promise.reject(new Error("not exist"));

test("rejects with foo", () => {
  return expect(fetchData("foo")).rejects.toThrow("not exist");
});

おわりに

jestを使えば、非同期処理のテストも簡単に書けますね!

3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?