最近我将应用程序升级到 Angular 17
仅当我发出测试命令时才会发生此错误
ng test
应用程序构建和执行工作正常,并且投入生产,一切都很好, 仅在茉莉花测试中我被阻止,是否有人遇到类似问题让我知道解决方法
Angular 17.0.0 代码
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ TestComponent ],
imports: [
CommonModule,
BrowserModule,
AppModule
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(HeaderComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
错误来自
at reportUnknownPropertyError (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2022/core.mjs:9036:15)
您收到错误,因为您将类型
TestComponent
分配给 component
变量,但实际上您正在创建 HeaderComponent
。分配 fixture.componentInstance
时存在类型不匹配。要修复它,只需创建正确的组件即可:
fixture = TestBed.createComponent(TestComponent);
当前接受的答案只是忽略了这个问题,并不可取。它不会使组件变得可测试。
我通过将模块代码
app.module.ts
复制到 app.module.spec.ts
解决了该问题
并用
schema
介绍CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA
部分如下
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
HttpClientXsrfModule,
HttpClientModule
],
bootstrap: [AppComponent],
schemas: [
CUSTOM_ELEMENTS_SCHEMA,
NO_ERRORS_SCHEMA
]
})
export class AppModule {}
并在 jasmine 代码中使用这个新模块
import { AppModule } from './app.module.spec';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
errorOnUnknownProperties: false,
imports: [
AppModule
]
}).compileComponents();
});
});