angular - 在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();
});
推荐阅读
- excel - VBA - 如何根据特定条件隐藏行?
- python - matplotlib 内联后端不允许我控制轴位置
- php - 在刀片文件中检索多对多关系数据
- json - ArcGIS Hub - JSON 堆积条形图
- php - 在 laravel 中设置自定义用户验证链接问题
- r - 如何使用“复制”防止使用循环
- python - 如何使用 Python 计算一长串特定列中不同值的存在?
- html - yahoo 邮件客户端删除了锚标记中的 href
- node.js - 我正在安装 puppeteer 库
- python - 如何使用 AJAX 在 django 中实现喜欢/不喜欢按钮(对于登录用户)