[英]Testing If FormBuilder has called the method group on NgOnInit()
I am new to angular and angular testing and I have gone through many articles on jasmine testing the formBuilder but did not get much help.我是 angular 和 angular 测试的新手,我已经阅读了许多关于 jasmine 测试 formBuilder 的文章,但没有得到太多帮助。
Assume I have the following code假设我有以下代码
ngOnInit(): void {
this.someForm = this.formBuilder.group({
formField1: [null, Validators.required],
formField2: [null, Validators.required],
formField3: [null, Validators.required]
});
}
Now I want to test if group method on formBuilder is called or not.现在我想测试是否调用了 formBuilder 上的 group 方法。 How can I do it in Jasmine angular?如何在 Jasmine angular 中做到这一点? I have tried the below code but it is not working:我已经尝试了下面的代码,但它不工作:
beforeEach(() => {
fixture = TestBed.createComponent(ChangePasswordComponent);
formBuilder = TestBed.inject(FormBuilder);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('on ngOnit_ FormBuilder object should call group method', () => {
fixture.detectChanges();
const spyObject = spyOn(formBuilder, 'group');
fixture.detectChanges();
expect(spyObject).toHaveBeenCalled();
});
The ngOnInit
is called when fixture.detectChanges
was first invoked after component creation (in beforeEach
here)! ngOnInit
在组件创建后首次调用fixture.detectChanges
时被调用(在beforeEach
中)!
So as you are spying on the form builder service after angular life cycle hooks are called there was no call to form builder's group
method.因此,当您在调用 angular 生命周期挂钩之后监视表单构建器服务时,没有调用表单构建器的group
方法。
Solution: As ngOnInit
is just a method called by angular, you can invoke it again yourself and assert.解决方案:由于ngOnInit
只是angular调用的一个方法,你可以自己再次调用并断言。
const spyObject = spyOn(formBuilder, 'group');
component.ngOnInit();
fixture.detectChanges();
expect(spyObject).toHaveBeenCalled();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.