はじめに
今回は、前回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