jestに入門してみた
プロジェクトにインストール。
yarn add —-dev jest
テストするfunctionを用意する。
sum.js
function sum(a, b) { return a + b; } module.exports = sum;
テストコードを書く。
sum.test.js
const sum = require('./sum'); test('1 + 2 = 3になること', () => { expect(sum(1, 2)).toBe(3); });
package.jsonに test scriptを追加。
{ “scripts”: { “Test”: “jest" } }
テストを実行。
yarn test
グローバルに追加しておくことで、cliからjestを実行できる
yarn global add jest
2つほど質問されたあと、jest.config.jsが作成された
jest —init
jest.config.jsの中には
module.exports = { ... clearMocks: true, ... testEnvironment: "node", };
とあった。質問の内容が反映されている。
プロジェクトでbabelを使う場合
yarn add —-dev babe-jest @babel/core @babel/preset-env
をインストール。
babel.config.jsを作成。
module.exports = { presets: [ [ '@babel/preset-env', { targets: { node: 'current', }, }, ], ], };
TypeScriptを使う場合
yarn add —dev @babel/preset-typescript
babel.config.jsのpresetsに
presets: [ ‘@babel/preset-typescript’, ]
を追記。
わからなかったこと
describe(name, fn)
- これから name のテストをするよ、という宣言。ネストすることもできる