3
3

More than 3 years have passed since last update.

【Jest入門】テストのグループ化

Posted at

はじめに

今回は、前回Jestが動く環境が作成できたので、テストのグループ化についてまとめたいと思います。

テストのグループ化

  • Jestではテストを定義するためにtest関数を使います。
  • test関数のエイリアスとして、it関数を利用することができます。
  • テストをグループ化するためには、describe関数を利用します。
  • テストをグループ化することで、グループ毎のテストができるようになり、わかりやすくなります。

describe関数で、it関数とtest関数をグループ化

下記のコードは、引数で受け取った値がbirdであればtrueを返し、それ以外はfalseを返す簡単なコードです。

src/group.js
export const isFly = (animal) => (animal === "bird" ? true : false);
src/group.test.js
import { isFly } from "./group";

describe("#isFly", () => {
  test("A bird can fly", () => {
    expect(isFly("bird")).toBe(true);
  });
  it("A horse can not fly", () => {
    expect(isFly("horse")).toBe(false);
  });
});

describeでテストの結果がグループ化され、わかりやすくなっていることが確認できます。

terminal
$ npm test /Users/jest-basic/src/group.test.js 

> jest-basic@1.0.0 test /Users/jest-basic
> jest "/Users/jest-basic/src/group.test.js"

 PASS  src/group.test.js
  #isFly
    ✓ A bird can fly (2 ms)
    ✓ A horse can not fly

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.384 s, estimated 1 s
Ran all test suites matching 
3
3
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
3