如何解决角度测试是否在ngOninit期间调用了组件方法?
我的目标是创建某些方法的间谍,并检查在ngOninit期间是否调用了这些方法以及pagePurpose是否等于Update。目前,我正在尝试设置间谍并在describe中设置component属性,然后尝试断言是否调用了函数,但我得到了:预期的间谍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();
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。