Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 为什么Jasmine expect().haveEncalled断言在没有包装器函数的情况下会失败_Angular_Jasmine - Fatal编程技术网

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?