jest を使ったテスト
以下のリンクが公式サイトです。
- app
- lib
- tax.js
- test
- tax.test.js
- lib
tax.js
const BigNumber = require('bignumber.js');
function tax_price (price){
return BigNumber(price).times(1.1);
}
module.exports = {
tax_price
}
tax.test.js
const { tax_price } = require('./../lib/tax');
describe('TestService', () => {
test('calc tax', () => {
const result = tax_price(100);
expect(result.toNumber()).toBe(110);
});
});
ルートディレクトリで以下のコマンドを実行します。
npx jest ./test/tax.test.js
以下がテスト結果です。
PASS test/tax.test.js
TestService
√ calc tax (3 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.407 s, estimated 1 s
Ran all test suites matching ./test/tax.test.js.
よく使うマッチャー
マッチャー(matcher) とは、expect(...) のあとに続けて書く、**「どう比較・検証するかを指定する関数」**です。
マッチャー | 用途 |
---|---|
.toBe(value) |
厳密比較(プリミティブ型) |
.toEqual(value) |
オブジェクト・配列の構造比較 |
toBeNull() |
null であること |
toBeUndefined() |
undefined であること |
toBeGreaterThan(n) |
より大きい(>) |
.toBeTruthy() |
真であること |
.toBeFalsy() |
偽であること |
.toContain(value) |
配列や文字列に含まれていること |
.toThrow() |
関数が例外を投げること |
構文イメージは、以下です。
expect(実際の値).マッチャー(期待する値);
テストサンプル
describe('TestService', () => {
test('test sample', () => {
const arr = [1, 2, 3, 4, 5];
expect(arr.length).toBe(5);
});
});