0
0

More than 1 year has passed since last update.

node jest導入(チュートリアル)

Posted at

jestを使う前にやること

まず、npmとnodeはインストールすること。
npmインストール:https://docs.npmjs.com/cli/v7/commands/npm-install  (参考)
nodeインストール:https://qiita.com/kyosuke5_20/items/c5f68fc9d89b84c0df09 (mac参考)

// プロジェクトのルートディレクトリで実行。空っぽのpackage-lock.jsonができる
npm install

// 指定したバージョン
nodebrew install-binary {version}
// 最新のバージョン
nodebrew install-binary latest

jestインストール

下記のコマンドでjestをインストールすると、package-lock.jsonにいろいろ設定が追加される。

npm install --save-dev jest

ファイルの作成

■テストしたいファイル作成(sum.js)

function sum(a, b) {
  return a + b;
}
module.exports = sum;

■テストファイル(sum.test.js)

const sum = require('./sum');
 
test('adds 1 + 2 to equal 3', () => {
  // expext(テストしたいメソッド名(第一引数, 第二引数)).toBe(returnされる値);
  expect(sum(1, 2)).toBe(3);
});

■pakage.jsonに追加

{
  "scripts": {
    "test": "jest"
  }
}

テストコマンド

以下のコマンドでテストを実行する

npm run test
[jest] npm run test                                                                                                                                                                                                                 14:44:36

> jest@1.0.0 test /Users/yamada-min/Desktop/study/code/jest
> jest

 PASS  ./sum.test.js
  ✓ adds 1 + 2 to equal 3 (1 ms)

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

テスト実行後、上記の様な結果になっていればテスト成功。
失敗した場合はFAILになり、どこがエラーになっているのか詳細もでてくる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0