JestでTypeScriptのテスト(最低限の設定)
【概要】
Jestを使ってTypeScriptのテストをやろうと思ったら、
なかなか上手くいかなかったのでメモを残しておく。
と言っても、参考サイトまんまな部分が多いです。
あと、yarnではなくnpmを使って環境を整えます。
【環境】
$ sw_vers ProductName: Mac OS X ProductVersion: 10.14.5 BuildVersion: 18F132 $ npm --version 6.9.2
【手順】
作業ディレクトリやらの作成・移動
$ mkdir typescript-jest-sample $ cd typescript-jest-sample $ mkdir src tests
必要なモノを揃える
$ npm init -y $ npm install --save-dev typescript jest ts-jest @types/jest $ npx ts-jest config:init $ ls jest.config.js package-lock.json src node_modules package.json tests
Jest設定ファイルの中身を確認
$ cat jest.config.js module.exports = { preset: 'ts-jest', testEnvironment: 'node', };
testコマンドの設定を変更
$ vim package.json { "name": "typescript-jest-sample", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { + "test": "jest" - "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@types/jest": "^24.0.18", "jest": "^24.9.0", "ts-jest": "^24.1.0", "typescript": "^3.6.3" } }
テストやらを書く
$ vim tests/greet.test.ts import greet from '../src/greet'; describe('greet', (): void => { it('should say hello to Ben.', (): void => { expect(greet('Ben')).toBe('Hello, Ben!'); }); });
$ vim src/greet.ts export default (name: string): string => `Hello, ${name}!`;
テストの実行
$ npm test > typescript-jest-sample@1.0.0 test /<PATH>/typescript-jest-sample > jest PASS tests/greet.test.ts greet ✓ should say hello to Ben. (2ms) Test Suites: 1 passed, 1 total Tests: 1 passed, 1 total Snapshots: 0 total Time: 0.505s, estimated 2s Ran all test suites.
やったぜ。おわり。