ng 服务命令导致错误"Cannot find name 'describe' (or 'beforeEach', 'it', 'expect', etc.)"



我正在尝试在我们构建的库上运行 Karma/Jasmine 单元测试(这是 Angular 版本 8(。单元测试运行良好(使用"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"、"期望"和"描述"方面遇到同样的错误。

我试过:

  • 重新安装所有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。

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

最新更新