这个错误通常是由于未正确配置测试环境导致的。以下是解决方法的示例代码:
npm install jest @types/jest jest-preset-angular --save-dev
jest.config.js
文件,并添加以下配置:module.exports = {
preset: 'jest-preset-angular',
setupFilesAfterEnv: ['/src/setup-jest.ts'],
globals: {
'ts-jest': {
tsconfig: '/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
astTransformers: {
before: ['jest-preset-angular/build/InlineFilesTransformer', 'jest-preset-angular/build/StripStylesTransformer']
}
}
}
};
src
目录下创建一个setup-jest.ts
文件,并添加以下内容:import 'jest-preset-angular/setup-jest';
tsconfig.spec.json
文件中添加以下配置:{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jest",
"node"
]
},
"files": [
"src/polyfills.ts"
],
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
app.component.spec.ts
文件中已正确导入AppComponent
,并且使用了正确的测试装饰器。示例代码如下:import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AppComponent],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create the app', () => {
expect(component).toBeTruthy();
});
});
npm test
命令来执行测试。如果一切配置正确,你将不再看到"无法解析AppComponent的所有参数"的错误。希望这些步骤能帮助你解决问题!