Describe is not defined exception on Typescript, Mocha 和 VSCode

Describe is not defined exception on Typescript, Mocha and VSCode

出于某种原因,我的 mocha 测试脚本抛出了异常 "describe is not defined"。

我已经阅读并尝试了这些 SO 问题建议的解决方案,但没有成功:
describe is not a function
"Mocha describe is not defined duplicate"

其他链接是:

这是我的VSCodelaunch.json。

{
  "type": "node",
  "request": "launch",
  "name": "Mocha Tests",
  "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
  "args": [
    "-u",
    "tdd",
    "--timeout",
    "999999",
    "--colors",
    "${workspaceRoot}/dist/tests/**/*.js"
  ],
  "outFiles": ["${workspaceFolder}/dist/tests/**/*.js"],
  "sourceMaps": true,
  "protocol": "inspector",
  "internalConsoleOptions": "openOnSessionStart"
}

这是我的 mocha 测试脚本:

import "mocha";
import assert = require("assert");

describe("Init", () => {
  before(() => {
    console.log("before-hook");
  });

  it("connected", () => {
    assert(true, "is not true");
  });
});

这是我的 tsconfig.json:

{
  "compilerOptions": {
    "experimentalDecorators": true,
    "strict": true,
    "noImplicitAny": false,
    "module": "commonjs",
    "target": "es6",
    "lib": [ "es6" ],
    "sourceMap": true,
    "outDir": "dist",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "strictNullChecks": true,
    "allowJs": false,
    "checkJs": false,
    "types": [
      "node"
    ]
  },
  "compileOnSave": true
}

我在这里做错了什么?我真的需要重新开始使用 mocha。

也许可以通过在 tsconfig.json

中的 types 中指定 mocha 来实现
{
  "compilerOptions": {
    ...
    "types": [
      "node",
      "mocha" <--- specify here
    ]
  },
  "compileOnSave": true
}

另外别忘了安装@types/mocha

npm install @types/mocha --save-dev

希望能解决您的问题

你的测试文件是用Javascript写的吗(你指的是你launch.json中的*.js)?

我正在使用 ts-node 调试单元测试,并直接引用 Typescript 测试文件,所以我的 launch.json 条目如下所示。在我使用 ts-node 之前,我在 VS Code 中收到 运行 时的 'describe is not defined' 错误。

{
  "type": "node",
  "request": "launch",
  "name": "Unit tests (mocha)",
  "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
  "args": [
    "-r",
    "ts-node/register",
    "--timeout",
    "999999",
    "--colors",
    "${workspaceFolder}/test/**/*Test.ts",
  ],
  "console": "integratedTerminal",
  "internalConsoleOptions": "neverOpen",
  "protocol": "inspector"
}

在这里回答我自己的问题。

我在安装Mocha 6.1.1 后解决了这个问题。

在 launch.json 上,将 args 数组从 "tdd" 更改为 "bdd" 以便:
"-u", "bdd"

版本 5.x 使用 "tdd" 选项,因此下一个主要版本导致了配置编写错误的问题。

删除此导入:

import { describe, it } from 'mocha';

似乎帮我修好了。