仕事でNode.js+Jest
を使った時に、調べた内容のメモです。
前提
環境
- OS:Windows10 Pro
Nodeのインストール
最終的なフォルダ構成
JestSample ├app/ │ ├sum.js(※1で作成) │ └__tests__/ │ └sum.test.js(※2で作成) ├node_modules(※3で作成) │ └ (省略) ├package.json(※4で作成) └package-lock.json(※3で作成)
ソースファイル(※1)
- Jestのリファレンスに記載されている一番簡単なサンプルプログラム
function sum(a, b) { return a + b; } module.exports = sum;
テストコード(※2)
- Jestのリファレンスに記載されている一番簡単なサンプルプログラム
// const sum = require('./sum'); const sum = require('../sum'); test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });
※ テストコードをapp/__tests__
ディレクトリに入れたのでテストコードから実コードにPathを通すための変更を実施しました。
Jestをインストールする
インストール(※3)
node_modules
フォルダが存在する階層で以下のコマンドを実行します。
(コマンドプロンプトでOK)
// npmなら npm install --save-dev jest
実行結果
>npm install --save-dev jest npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142 npm WARN deprecated request-promise-native@1.0.9: request-promise-native has been deprecated because it extends the now deprecated request package, see https://github.com/request/request/issues/3142 npm WARN deprecated har-validator@5.1.5: this library is no longer supported npm WARN saveError ENOENT: no such file or directory, open 'D:\******\JestSample\package.json' npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^2.1.2 (node_modules\jest-haste-map\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm WARN enoent ENOENT: no such file or directory, open 'D:\******\JestSample\package.json' npm WARN JestSample No description npm WARN JestSample No repository field. npm WARN JestSample No README data npm WARN JestSample No license field. + jest@26.6.3 added 520 packages from 355 contributors and audited 521 packages in 42.12s 24 packages are looking for funding run `npm fund` for details found 0 vulnerabilities
package.json
の作成(※4)
{ "scripts": { "test": "jest" } }
Jestの実行
npm test
実行結果
>npm test > @ test D:\******\JestSample > jest PASS app/__tests__/sum.test.js √ adds 1 + 2 to equal 3 (2 ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 1.243 s Ran all test suites.