[英]How to unit test a component
我正在Angular App上運行單元測試,但是組件尚未初始化。 它需要三個參數,我將模擬服務,但是前兩個參數呢?
import { HttpClient } from '@angular/common/http';
import { NgxSpinnerService } from 'ngx-spinner';
constructor(private http: HttpClient,
private spinner: NgxSpinnerService,
private someService: SomeService) {
}
預期:組件應創建
實際:未創建組件
為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.