ng serve命令导致错误“找不到名称'describe'(或'beforeEach','it','expect'等)”

时间:2019-08-29 23:09:29

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

我正在尝试在我们构建的库(这是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文件中导入“茉莉花”。
  • 按照错误消息的指示安装@ 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。

1 个答案:

答案 0 :(得分:3)

重现此错误的一种方法是将您的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文件中编写了测试。