expect
/ matcher の使い方Jestで結果をチェックするときは
expect(実際の値)
.toBe(期待する値)
などの matcher(マッチャ)
をセットで使います。
マッチャは
数値
文字列
オブジェクト
配列
関数の呼び出し回数
など色々なパターンをチェックできます。
// 実際の値が期待する値と一致するかチェック
expect(実際の値).toBe(期待する値);
matcher | 意味 | 例 |
---|---|---|
toBe |
=== で比較 | expect(1 + 2).toBe(3) |
toEqual |
オブジェクトや配列の中身まで比較 | expect({ a: 1 }).toEqual({ a: 1 }) |
toBeTruthy |
true かどうか | expect(true).toBeTruthy() |
toBeFalsy |
false かどうか | expect(false).toBeFalsy() |
toContain |
配列や文字列に含まれているか | expect([1, 2, 3]).toContain(2) |
toHaveLength |
配列や文字列の長さ | expect([1, 2, 3]).toHaveLength(3) |
toThrow |
エラーを投げるか | expect(() => { throw new Error() }).toThrow() |
toMatchSnapshot |
スナップショットと一致するか | (次の章で解説) |