使用Jest调试TypeScript代码

462 阅读1分钟

本人最近正在听CoderWhy的数据结构与算法, 为了方便测试使用了Jest进行测试.

一开始使用ts-node进行debug, 后来觉得都使用Jest了, 为什么不用Jest进行debug, 经过一点探索, 就有了今天这篇文章.

1. VS Code安装Debugger for Jest插件

2. 安装相关依赖

npm install --save-dev jest typescript ts-jest @types/jest

npx typescript init

3. 配置jest.config.js

module.exports = {
    transform: {
        '^.+\\.jsx?$': 'babel-jest'
    },
    preset: 'ts-jest',
    testEnvironment: 'node',
    globals: {
        'ts-jest': {
            tsconfig: 'tsconfig.json'
        }
    },
}

4. 配置VS Code启动文件launch.json

  • 项目根目录下创建.vscode文件夹, 将launch.json文件放入其中:
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Jest Current File",
      "program": "${workspaceFolder}/node_modules/jest/bin/jest.js",
      "args": [
        "${relativeFile}",
        "--config",
        "jest.config.js"
      ],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen"
    }
  ]
}
  • 注意: 我的开发环境是Mac下的Docker, 如果你是Windows环境需要将program字段修改为"program": "${workspaceFolder}/node_modules/.bin/jest",

5. 开始调试

  • 在需要debug的xxx.test.ts项目中打上断点, 然后运行Jest Current File即可调试.

image.png

最后附上我的项目代码, 欢迎Star

github.com/tsja2001/ty…