コンテンツにスキップ

単体テストを書く

04 章 単体テストを書く

前の節で設計した表のうち、ふつうの場合の S1(split)と B1(balances)をテストに書いて動かします。

テストは、Podman ではなく手元の Node.js で動かします。apps/api/ で、ライブラリを入れます。

ターミナルウィンドウ
cd apps/api
npm install

テストの道具の Vitest は、nest new がはじめから入れています。新しく入れるものはありません。

ファイル 中身
package.json devDependencies に vitest。scripts の test は vitest run
vitest.config.ts include: ['**/*.spec.ts']。名前が .spec.ts で終わるファイルをテストとして動かす

そこで、単体テストのファイルは、確かめるファイルの隣に <名前>.spec.ts の名前で置きます。settle.ts のテストは settle.spec.ts です。

apps/api/src/settlement/settle.spec.ts を作成する

Section titled “apps/api/src/settlement/settle.spec.ts を作成する”
apps/api/src/settlement/settle.spec.ts
1
import { describe, expect, it } from 'vitest';
2
import { balances, split } from './settle.js';
3
4
describe('split', () => {
5
// S1
6
it('割り切れるときは、同じ額に分ける', () => {
7
expect(split(9000, 3)).toEqual([3000, 3000, 3000]);
8
});
9
});
10
11
describe('balances', () => {
12
// B1
13
it('払った人はプラス、対象の人はマイナスになる', () => {
14
const result = balances([
15
{ payerId: 1, amount: 9000, participantIds: [1, 2, 3] },
16
]);
17
18
expect(result).toEqual([
19
{ memberId: 1, amount: 6000 },
20
{ memberId: 2, amount: -3000 },
21
{ memberId: 3, amount: -3000 },
22
]);
23
});
24
});
  • describe('split', ...) … テストをまとめる箱です。関数ごとに分けます
  • it('...', () => { ... }) … テスト 1 つです。名前には「どうなるべきか」を書きます。テストが落ちたとき、この名前が表示されます
  • expect(結果).toEqual(期待する結果) … 結果が期待どおりかを、配列やオブジェクトの中身まで比べて確かめます
  • // S1・// B1 … 設計の表の番号です。表とテストを行き来できるように付けておきます
ターミナルウィンドウ
npm test
✓ src/settlement/settle.spec.ts (2 tests) 2ms
Test Files 1 passed (1)
Tests 2 passed (2)

試しに、S1 の期待する結果を [3000, 3000, 3001] にまちがえて、npm test を動かします。

FAIL src/settlement/settle.spec.ts > split > 割り切れるときは、同じ額に分ける
AssertionError: expected [ 3000, 3000, 3000 ] to deeply equal [ 3000, 3000, 3001 ]
- Expected
+ Received
[
3000,
3000,
- 3001,
+ 3000,
]

落ちたテストの名前と、期待する結果(Expected)と実際の結果(Received)の違いが出ます。確かめたら、[3000, 3000, 3000] に戻します。

この節は、次の公式ドキュメントをもとに書いています。

この節を終えたときのディレクトリ

Section titled “この節を終えたときのディレクトリ”
この節を終えた状態をダウンロード
npm install で npm warn や vulnerabilities と出る

ライブラリについてのお知らせで、エラーではありません。そのまま進めます。