【发布时间】:2021-02-04 11:38:33
【问题描述】:
我的目标是创建某些方法的 spy,并检查这些方法是否在 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();
});
非常感谢您的帮助!
【问题讨论】:
-
const spy = spyOn(component, 'createLineReviewRequest');期望(间谍).toHaveBeenCalled();
-
不要窥探你要测试的东西。测试什么,例如
this. createLineReviewRequest(...)应该做。 -
@jonrsharpe 这对我来说很有意义,所以我退后一步并尝试断言:expect(component.canContinue).toBeTruthy();看看我是否进入 if 语句进行测试,我得到预期未定义是真实的。我不确定为什么它未定义。
-
我很惊讶 TypeScript 甚至允许你这样做,
ReportsModalLineReviewComponent没有定义canContinue属性。 -
好像我在粘贴代码时忘记包含它了,这是我的问题。
标签: angular unit-testing jasmine ngoninit