【问题标题】:ng serve command causes error "Cannot find name 'describe' (or 'beforeEach', 'it', 'expect', etc.)"ng serve 命令导致错误“找不到名称'describe'(或'beforeEach'、'it'、'expect'等)”
【发布时间】:2020-01-03 05:34:46
【问题描述】:

我正在尝试在我们构建的库(这是 Angular 版本 8)上运行 Karma/Jasmine 单元测试。单元测试运行良好(使用“ng test”),但是当我尝试编译(ng build)时,出现以下错误:

Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig.

对于“beforeEach”、“it”、“expect”和“describe”,我遇到了同样的错误。

我试过了:

  • 重新安装所有 node_module 文件。
  • 在 spec.ts 文件中导入“jasmine”。
  • 按照错误消息的指示安装@types/jest 和@types/mocha。
  • 将这两个模块以及一些其他已安装的模块添加到 tsconfig.json 中的“类型”列表中(请参阅文章末尾的文件)。
  • 验证 node_modules@types\jasmine 中的 index.d.ts 文件是否包含我收到错误的方法的定义。

只是基本的、自动生成的测试文件会导致编译错误:

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ]
    }).compileComponents();
  }));

  it('should create the app', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  });
});

这是 tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "types": [
      "jest",
      "node",
      "jasmine",
      "jasminewd2",
      "mocha"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

仅供参考,我正在运行 TypeScript 3.5.3、Karma 4.1.0 和 Jasmine 3.4.0。

【问题讨论】:

  • 您的每种类型都有哪些版本?您可能使用的是过时的版本。此外,如果您不使用这些类型,则不需要 jest/mocha。错误是给你一个建议。 Describe 是已经属于 jasmine 的函数了。
  • 节点是8.9.4,Jasmine是3.4.0,jasminewd2是2.0.3。
  • 刚刚检查过,Node 已经过时了相当多的版本。我会尝试更新它并报告它是如何工作的。
  • 没有骰子。仍然给出相同的错误。

标签: angular typescript unit-testing jasmine karma-runner


【解决方案1】:

重现此错误的一种方法是在 src/tsconfig.app.json 文件中注释掉一行。

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": []
  },
  "exclude": [
    "test.ts",
    // "**/*.spec.ts" <-- commenting this out loads your spec, which isn't what you want for npm start
  ]
}

另一种可能是你错误地命名了一个规范文件,因此这个过滤器不会将它排除在外,或者你已经在一个实际的.ts 文件中编写了测试。

【讨论】:

  • 原来是一个错误的规范文件。感谢您的回复!
猜你喜欢
  • 2020-11-28
  • 2010-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多