我正在尝试在我们构建的库(这是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',我也遇到同样的错误。
我尝试过:
自动生成的基本测试文件会导致编译错误:
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。
答案 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
文件中编写了测试。