[英]How to unit test a component
I am running unit test on Angular App, But the component is not getting intialized. 我正在Angular App上运行单元测试,但是组件尚未初始化。 It needs three paramaters, I will mock the service but what about the first two parameters?
它需要三个参数,我将模拟服务,但是前两个参数呢?
import { HttpClient } from '@angular/common/http';
import { NgxSpinnerService } from 'ngx-spinner';
constructor(private http: HttpClient,
private spinner: NgxSpinnerService,
private someService: SomeService) {
}
Expected: Component should create 预期:组件应创建
Actual: Component is not created 实际:未创建组件
import HttpClientTestingModule for httpClient and add NgxSpinnerModule in your imports too 为httpClient导入HttpClientTestingModule,并在导入中也添加NgxSpinnerModule
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { NgxSpinnerModule } from 'ngx-spinner';
...
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule, // for httpClient
NgxSpinnerModule
],
declarations: [ YourComponent],
providers: [service],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
}));
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { NgxSpinnerModule } from 'ngx-spinner';
...
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule, // for httpClient
NgxSpinnerModule
],
declarations: [ YourComponent],
providers: [service],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(async() => {
fixture = TestBed.createComponent(AnalyticsComponent);
component = fixture.componentInstance;
// @Inputs
component.metric = 'sales';
component.ngOnInit(); // <===== importand
component.ngAfterViewInit(); // <===== importand
await fixture.whenStable(); // <===== importand
fixture.detectChanges(); // <===== importand
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.