如何对组件进行单元测试

时间:2019-03-29 08:48:35

标签: angular unit-testing

我正在Angular App上运行单元测试,但是组件尚未初始化。它需要三个参数,我将模拟服务,但是前两个参数呢?

import { HttpClient } from '@angular/common/http';
import { NgxSpinnerService } from 'ngx-spinner';

constructor(private http: HttpClient,
    private spinner: NgxSpinnerService,
    private someService: SomeService) {
    }

预期:组件应该创建

实际:未创建组件

2 个答案:

答案 0 :(得分:0)

为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;
}));

答案 1 :(得分:0)

是组件!!您应该使用这种模式。

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
});