[英]Angular 9 testing in jasmine: Testing a child component's service method
[英]testing child component ngOnChanges in angular jasmine
我正在嘗試為具有 ngOnChanges @Input 的 angular child 編寫單元測試。 我在這篇文章中使用了方法在此處輸入鏈接描述
我的代碼如下。
import { Component, NO_ERRORS_SCHEMA, SimpleChange } from '@angular/core';
import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { ShipmentCardComponent } from './shipment-card.component';
@Component({
template: `<nfx-shipment-card [shipmentData]="{}" [index]="index"></nfx-shipment-card>`,
})
export class TestWrapperComponent {
shipmentData: any;
index: number;
}
describe('ShipmentCardComponent', () => {
let component: TestWrapperComponent;
let fixture: ComponentFixture<TestWrapperComponent>;
let element: any;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
ShipmentCardComponent,
TestWrapperComponent,
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestWrapperComponent);
component = fixture.componentInstance;
element = fixture.nativeElement;
});
afterEach(() => {
fixture.destroy();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should trigger lifecycle hooks', () => {
component.index = 0;
component.shipmentData = {};
fixture.detectChanges();
});
it('should trigger toggle', () => {
component.index = 0;
component.shipmentData = {};
fixture.detectChanges();
element.toggle();
});
});
不,我的問題是在我的子nfx-shipment-card
組件中,我有toggle
方法,我該如何調用它?
您可以使用By
選擇器並選擇nfx-shipment-card
。
1.) 在beforeEach
使用By.directive
的beforeEach
2.) 調用切換方法。
import { By } from '@angular/platform-browser';
......
describe('ShipmentCardComponent', () => {
let component: TestWrapperComponent;
let shipmentCard: ShipmentCardComponent; // add this line
let fixture: ComponentFixture<TestWrapperComponent>;
let element: any;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
ShipmentCardComponent,
TestWrapperComponent,
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestWrapperComponent);
component = fixture.componentInstance;
shipmentCard = fixture.debugElement.query(By.directive(ShipmentCardComponent)).componentInstance;
// add the line above to have access to the element
element = fixture.nativeElement;
});
afterEach(() => {
fixture.destroy();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should trigger lifecycle hooks', () => {
component.index = 0;
component.shipmentData = {};
fixture.detectChanges();
});
it('should trigger toggle', () => {
component.index = 0;
component.shipmentData = {};
fixture.detectChanges();
element.toggle();
shipmentCard.toggle(); // you should have access to its public methods and properties like so.
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.