Skip to main content

JavaScript + Jest

方針

  • TypeScript のテストランナーとして Jest + ts-jest を使う
  • CommonJS ( require ) で最小構成にする

前提

  • Node.js, npm がインストール済であること
bash
brew install node
brew install npm

プロジェクト作成

bash
mkdir -p ~/workdir/SampleTsJest
cd ~/workdir/SampleTsJest
npm init -y
npm i -D jest ts-jest typescript @types/jest
npm pkg set scripts.test="jest"
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
}
}
jest.config.js
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
testMatch: ["**/test/**/*.test.ts"]
};

最小のコード

src/sample.ts
export function add(a: number, b: number): number {
return a + b;
}
__tests__/sample.test.ts
import { add } from "../src/sample";

test("add two and three", () => {
expect(add(2, 3)).toBe(5);
});

決まりごと

  • ファイル名: test/*.test.ts
  • テスト: test("<名前>", () => { ... }) または it(...)
  • 期待値: expect(<値>).toBe(<期待>) など

実行

bash
npm test

実行結果

txt
% npm test

> sampletsjest@1.0.0 test
> jest

PASS test/sample.test.ts
✓ add two and three (2 ms)

Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.976 s
Ran all test suites.

以下広告