Angular 为什么Jasmine expect().haveEncalled断言在没有包装器函数的情况下会失败
如果我有这样的订阅Angular 为什么Jasmine expect().haveEncalled断言在没有包装器函数的情况下会失败,angular,jasmine,Angular,Jasmine,如果我有这样的订阅 this.submit$.subscribe(this.handleSubmit); it('should set up a subscription on submit$', () => { spyOn(component, 'handleSubmit'); component.submits$.next(data); expect(component.handleSubmit).toHaveBeenCalledTimes(1); expect(co
this.submit$.subscribe(this.handleSubmit);
it('should set up a subscription on submit$', () => {
spyOn(component, 'handleSubmit');
component.submits$.next(data);
expect(component.handleSubmit).toHaveBeenCalledTimes(1);
expect(component.handleSubmit).toHaveBeenCalledWith(data);
});
我这样测试它
this.submit$.subscribe(this.handleSubmit);
it('should set up a subscription on submit$', () => {
spyOn(component, 'handleSubmit');
component.submits$.next(data);
expect(component.handleSubmit).toHaveBeenCalledTimes(1);
expect(component.handleSubmit).toHaveBeenCalledWith(data);
});
我得到这个错误:
错误:应已调用spy handleSubmit一次。它被调用了0次。
如果我改为为为subscribe回调创建一个新的匿名函数,那么一切都会正常工作:
this.submit$.subscribe(data => this.handleSubmit(data));
为什么我需要创建此额外函数才能通过测试?
this.submit$.subscribe(this.handleSubmit)
在构造函数中。当我在测试中调用spyOn(component,'handleSubmit')
时,构造函数已经被调用,订阅已经创建。即使我现在在handleSubmit
上有一个间谍,订阅总是会调用原始的handleSubmit
当使用匿名函数作为订阅回调时,this.submit$.subscribe(数据=>this.handleSubmit(数据))
订阅与该匿名函数绑定。这使我能够在调用前监视handleSubmit
,因为匿名函数在submit$emits之前不会被调用
我通过移动
this.submit$.subscribe(this.handleSubmit)解决了这个问题
到ngOnInit,以便我可以控制何时创建订阅。此.submit$.subscribe(this.handleSubmit)
位于构造函数中。当我在测试中调用spyOn(component,'handleSubmit')
时,构造函数已经被调用,订阅已经创建。即使我现在在handleSubmit
上有一个间谍,订阅总是会调用原始的handleSubmit
当使用匿名函数作为订阅回调时,this.submit$.subscribe(数据=>this.handleSubmit(数据))
订阅与该匿名函数绑定。这使我能够在调用前监视handleSubmit
,因为匿名函数在submit$emits之前不会被调用
我通过移动
this.submit$.subscribe(this.handleSubmit)解决了这个问题
到ngOnInit,以便我可以控制订阅的创建时间。是因为订阅在我创建spy时已绑定到true component.handleSubmit?是因为订阅在我创建spy时已绑定到true component.handleSubmit?