簡體   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