LoginSignup
11
9

More than 5 years have passed since last update.

VSCode debugger + Jest

Posted at
  • やりたいこと: create-react-app-typescript で作った TypeScript プロジェクトの単体テストを Visual Studio Code でデバッグしたい。
  • 出来たこと: Javascript と Jest の組み合わせ
  • 出来なかったこと: Typescript と Jest の組み合わせ。create-react-app の組み合わせ。

適当に始めて vscode の typescript デバッガが使えない事に悩んでいたが、もう一度心を落ち着けて最初からチュートリアルをやってみることにした。

Javascript の開発とデバッグ

まずは、vscode を使ったデバッグに最低限必要な物を確認するため、 Node.js Tutorial in VS Code のチュートリアルを試す。

この記事によると以下が必要という事になる。

  • Javascript インタプリタ node.js をインストールしておく
  • Debug 起動設定ファイル .vscode/launch.json で実行ファイルを指定する。

.vscode/launch.json なしでデバッグしてみる。

$ mkdir hello
$ cd hello
$ code hello.js

var msg = 'hello world';
console.log(msg);

$ node hello.js 
hello world
  • Breakpoint 設定
  • View > Debug > 再生ボタン > node.js を選ぶ
  • これで今開いている js ファイルを node.js が実行する。

.vscode/launch.json を使ってデバッグ

View > Debug > 歯車ボタンで Debug 設定ファイル .vscode/launch.json の編集を行う。

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceRoot}/hello.js"
        }
    ]
}

デフォルトで実行プログラムは "program": ${file} になっているが、これは開いているファイルの意味。ここを例えば

"program": "${workspaceRoot}/hello.js"

に変えれば再生ボタンを押した時に必ず hello.js を実行する。

vscode と jest の連携

テスト用のプログラムを作る

mkdir jesttest
cd jesttest
yarn init
yarn add --dev jest

code hello.test.js
function add(a, b) {
  return a + b;
}

test('3 + 4 = 7', () => {
  expect(add(3, 4)).toBe(7);
});

package.json に登録すると、yarn test でテストを実行出来る。

code package.json
  "scripts": {
    "test": "jest"
  }
$ yarn test

これを vscode の debugger で動かすには .vscode/launch.json を以下のように設定する。program で jest のフルパスを指定するのと、--runInBand を指定するのがコツ。ブレークポイントも動く。

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "program": "${workspaceRoot}/node_modules/jest/node_modules/.bin/jest",
            "args": ["--runInBand"]
        }
    ]
}
11
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
9