Jestで書かれたテストコードをVisual Studio Codeでデバッグする

Posts

Jestで書かれたテストコードをVisual Studio Code上でデバッグする方法について説明します。

Jest のドキュメントにはlaunch.jsonに設定を記述するとなっています。 ですが、VSCodeの拡張「Jest Runner」を入れるだけで、以下ができます。

  • シナリオ単位でのテストを実行する
  • breakpointを設定してデバッグする

動作を確認した環境

  • Visual Studio Code v1.41.0
  • Jest Runner v0.4.11

Jest Runnerのインストール

  1. Visual Studio Codeで拡張機能のメニューを開きます。
  2. 検索窓に「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('');
      });
    });
    

シナリオ単位でのテストを実行する

  1. 実行したいテストにカーソルを合わせ、右クリックします。
  2. 右クリックメニューから「Run Jest」を選択します。
  3. カーソルを合わせたテストのみ実行されます。
    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を設定してデバッグする

  1. breakpointを設定します。例では7行目に設定しています。
  2. コード上で右クリックします。
  3. 右クリックメニューから「Debug Jest」を選択します。
  4. 設定したbreakpointでテストが一時停止します。 変数にカーソルを合わせると、内容を確認できます。

まとめ

難しい設定を書かなくても、VSCodeの拡張を入れるだけで、シナリオ単位での実行やテストのデバッグができるようになりました。