简体   繁体   English

Angular2单元测试服务,在构造函数时发出值

[英]Angular2 Unit test Service that Emit value at Constructor Time

Writing a unit test for a component, that uses a Service with an emit inside the constructor, like this: 编写一个组件的单元测试,该组件使用在构造函数内部使用带有辐射的Service,如下所示:

@Injectable()
export class Service1 {
  public onService1Done: EventEmitter<any> = new EventEmitter();
  public constructor(...) {
    this.onService1Done.emit(value);
  }
}

I notice that, according to what i have in the component.spec.ts: 我注意到,根据我在component.spec.ts中的内容:

beforeEachProviders(() => {
  return [
    provide(Service1, { useClass: MockService1 }),
    Component1
  ];
});

  it("check that XXX", inject(
    [Service1, Component1], (service1: Service1, component1: Component1) => {
    service1.onService1Done.subscribe({ next: () => DoSomething() });
    expect(DoSomething()).toEqual(IsDone);
  }));
});
}

The constructor of Service1, and so the emit, will be called before i could make the subscribe, inside the test; 在我可以在测试内部进行订阅之前,将调用Service1的构造函数(即emit);

there is a way to avoid this ?? 有一种方法可以避免这种情况? to make the subscribe before the Constructor ? 在构造函数之前进行订阅?

As always, thanks in advance. 一如既往,在此先感谢。

I don't see how anything could subscribe in any way to get this event when the service instance is created by DI. 我看不到当DI创建服务实例时,有什么东西可以通过任何方式订阅此事件。

Just don't emit it in the constructor or at least use some setTimeout(...) than at least synchronically executing code has a chance to subscribe if you must. 只是不要在构造函数中发出它,或者至少使用一些setTimeout(...) ,否则如果需要,至少同步执行代码有机会订阅。

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

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