[英]Angular testing if component method is called during ngOninit?
我的目標是創建某些方法的間諜,並檢查在 ngOninit 期間是否調用了這些方法以及 pagePurpose 是否等於 Update。 目前我試圖設置間諜並在描述中設置組件屬性,然后嘗試斷言是否調用了函數,但我得到:預期的間諜 createLineReviewRequest 已被調用。 我覺得我在創建間諜但沒有正確使用它們。 我也需要使用 highlight 方法來執行此操作,請注意,對於我的情況,我不在乎傳遞了什么方法。
我的組件如下:
export class ReportsModalLineReviewComponent implements OnInit {
pagePurpose: string;
canContinue: boolean ;
constructor() { }
ngOnInit() {
if (this.pagePurpose === "Update" ) {
this.highlight(this.dialogData.oldReport.lineReviewRequest.lineReviewFile.fileId)
this.createLineReviewRequest(this.dialogData.oldReport.lineReviewRequest.lineReviewFile);
this.canContinue = true;
}
}
Mt測試如下:
beforeEach(() => {
fixture = TestBed.createComponent(ReportsModalLineReviewComponent);
component = fixture.componentInstance;
component.pagePurpose = "Update";
spyOn(component, 'createLineReviewRequest');
fixture.detectChanges();
});
fit('should check if Update', () => {
expect(component.createLineReviewRequest).toHaveBeenCalled();
});
非常感謝您的幫助!
onInit 需要手動調用
我建議按照慣例進行單元測試。 給定 -> 當 -> 那么
let component: ReportsModalLineReviewComponent;
let fixture: ComponentFixture<ReportsModalLineReviewComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [CommonModule],
declarations: [ReportsModalLineReviewComponent]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ReportsModalLineReviewComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
fit('should check if Update', () => {
// GIVEN
component.pagePurpose = "Update";
spyOn(component, 'createLineReviewRequest');
// WHEN
component.ngOnInit()
// THEN
expect(component.createLineReviewRequest).toHaveBeenCalled();
});
如果有人可能會遇到這個問題:
錯誤: : 預期是間諜,但得到了函數。
為了解決它,我改變了
這個:
component.ngOnInit();
expect(component.someMethod).toHaveBeenCalled();
對此:
const spy = spyOn(component,'someMethod');
component.ngOnInit();
expect(spy).toHaveBeenCalled();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.