Skip to main content

JavaScript + Jest

方針

  • JavaScript (Node.js) のテストランナーとして Jest を使う
  • CommonJS ( require ) で最小構成にする

前提

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

プロジェクト作成

bash
mkdir -p ~/workdir/SampleJsJest
cd ~/workdir/SampleJsJest
npm init -y
npm i -D jest
npm pkg set scripts.test="jest"

最小のコード

src/sample.js
function add(a, b) {
return a + b;
}

module.exports = { add };
__tests__/sample.test.js
const { add } = require("../src/sample");

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

決まりごと

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

実行

bash
npm test

実行結果

txt
% npm test                   

> samplejsjest@1.0.0 test
> jest

PASS __tests__/sample.test.js
✓ add two and three (1 ms)

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

以下広告