Jest
セットアップ
TypeScriptで使う場合、以下をインストール
$ npm i jest @types/jest ts-jest -D
スナップショットテストを実施する場合は、以下をインストール
$ npm install -D react-test-renderer @types/react-test-renderer
jest.config.jsの設定
$ ts-jest config:init
code:jest.config.js
module.exports = {
preset: "ts-jest",
testEnvironment: "jsdom",
};
package.jsonの設定
code:package.json
{
"test": "jest"
}
setupTests.ts
code:setupTest.ts
import "@testing-library/jest-dom/extend-expect";
ref
基本形
code:ts
test('one plus two is three', () => {
expect(1 + 2).toBe(3);
});
テストをまとめる
describeを使う
code:ts
describe('plus', ()=> {
it('one plus two is three', () => {
expect(1 + 2).toBe(3);
});
it('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
})
入れ子にもできる
testとit
itはtestのエイリアス
describeと一緒に使うときはitが使われる傾向あるかも?
テストの下準備をする
beforeEachを使う
code:ts
describe('plus', ()=> {
beforeEach(() => {
// 下準備
});
it('', () => {});
})
beforeAllもあるけど、使うだろうか?rmaruon.icon
テストの後処理を行う
afterEachを使う
マッチャー
よく使う
toBe
Object.isで比較する
プリミティブな値の比較に使う
toEqual
再帰的に値をチェックする
オブジェクトの比較に使う
not
スナップショット
ref
見やすい