繁体   English   中英

如何对组件进行单元测试

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM