简体   繁体   English

为什么Angular中的Jasmine间谍功能没有被回调触发?

[英]Why Jasmine spy function in Angular is not being triggered by callback?

I want to test this.communication.subscribe() call which is having a callback in argument: 我想测试this.communication.subscribe()调用,该调用在参数中具有回调:

constructor (private communication: CommunicationProvider)

ngOnInit() {
    this.communication.subscribe(() => {
      this.router.navigate(["/success"]);
    });
  }

I have used callFake to mock the implementation to call callback() 我已经使用callFake模拟实现以调用callback()

beforeEach(async(() => {
    communicationSpy = jasmine.createSpyObj("CommunicationProvider", ["subscribe"]);
    routerSpy = jasmine.createSpyObj<Router>("Router", ["navigate"]);

    communicationSpy.subscribe.and.callFake((callback: any) => {
        callback();
    });
}));

it("should route on callback", (done: DoneFn) => {
    setTimeout(() => {
        expect(routerSpy.navigate).toHaveBeenCalledWith(["/success"]);
        done();
    }, 3000);
});

As per code coverage results, this.router.navigate(["/success"]); 根据代码覆盖范围的结果, this.router.navigate(["/success"]); is being covered by callback() . callback()覆盖。 But "should route on callback" test is failing as routerSpy.navigate is never being called. 但是, "should route on callback" routerSpy.navigate"should route on callback"测试失败,因为从未调用routerSpy.navigate

Why? 为什么?

Because you never trigger the subscription. 因为您永远不会触发订阅。

I don't know what your service is, but we'll take advantage of the fact that you don't use restriction operators such as take or takeUntil . 我不知道您的服务是什么,但是我们将利用您不使用诸如taketakeUntil类的限制运算符这一takeUntil

Start by mocking your observable as a hot stream with a Subject : 首先将您的可观察对象模拟为带有Subject的热流:

component['communication'] = new Subject() as any;

Now, you should have a new instance of your component in every test thanks to the fixture createComponentInstance called in the before each. 现在,由于在每个测试之前都调用了夹具createComponentInstance ,因此您应该在每个测试中都有一个新的组件实例。 This means you already have called ngOnInit and created the subscription. 这意味着您已经调用了ngOnInit并创建了订阅。

Since the stream is hot, you can subscribe to it in your test : 由于流很热,因此您可以在测试中订阅它:

it('should navigate', done => {
  component['communication'].subscribe(() => {
    expect(routerSpy.navigate).toHaveBeenCalledWith(["/success"]);
    done();
  });

  (component['communication'] as Subject).next(true);
});

With the next call, you trigger the subscriptions, launching the router and expecting it to have been called. next呼叫中,您触发订阅,启动路由器并期望已被呼叫。

(PS : I have used array syntax and Subject to picture the issue, feel free to use whatever you want to trigger a subscription and to mock your dependencies) (PS:我已经使用数组语法和Subject ,以图片的问题,随意使用任何你想要触发订阅和嘲笑你的依赖)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM