概要
Jest で書かれたテストコードを Visual Studio Code 上でデバッグする方法について説明します。
Jest のドキュメントには launch.json
に設定を記述するとなっています。
ですが、VSCode の拡張「Jest Runner」を入れるだけで、以下ができます。
- シナリオ単位でのテストを実行する
- breakpoint を設定してデバッグする
環境
- Visual Studio Code v1.41.0
- Jest Runner v0.4.11
Jest Runner のインストール
- Visual Studio Code で拡張機能のメニューを開きます。
- 検索窓に「Jest Runner」と入力して検索し、Jest Runner をインストールします。
動作確認用のコード
次のコードで動作を確認します。
- テスト対象のコード
const uppercase = (str) => {
if (!str || typeof str !== 'string') {
return '';
}
return str.toUpperCase();
}
module.exports = uppercase;
テストコード
const uppercase = require('./uppercase'); describe('uppercase', () => { test('with empty', () => { const str = ''; const result = uppercase(str); expect(result).toBe(''); }); test('with not empty', () => { const str = 'hello'; expect(uppercase(str)).toBe('HELLO'); }); test('with not a string', () => { const str = 7; expect(uppercase(str)).toBe(''); }); });
シナリオ単位でのテストを実行する
cd '/Users/chick-p/playground/debug-jest-sample'; node '/Users/chick-p/playground/debug-jest-sample/node_modules/.bin/jest' '/Users/chick-p/playground/debug-jest-sample/src/uppercase.test.js' -t '^uppercase with empty$'
PASS src/uppercase.test.js
uppercase
✓ with empty (4ms)
○ skipped with not empty
○ skipped with not a string
Test Suites: 1 passed, 1 total
Tests: 2 skipped, 1 passed, 3 total
Snapshots: 0 total
Time: 3.697s
Ran all test suites matching /\/Users\/chick-p\/playground\/debug-jest-sample\/src\/uppercase.test.js/i with tests matching "^uppercase with empty$".
breakpoint を設定してデバッグする
まとめ
難しい設定を書かなくても、VSCode の拡張を入れるだけで、シナリオ単位での実行やテストのデバッグができるようになりました。