0

Writing a unit test for a component, that uses a Service with an emit inside the constructor, like this:

@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:

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;

there is a way to avoid this ?? to make the subscribe before the Constructor ?

As always, thanks in advance.

AntuJitsu
  • 119
  • 1
  • 9
  • Why do you need to emit in the constructor? Besides that [you shouldn't use EventEmitter in your services](http://stackoverflow.com/questions/36076700/what-is-the-proper-use-of-an-eventemitter). Use plain Observables. – Eric Martinez Mar 25 '16 at 12:06
  • So, if I'm correctly understand, No EventEmitter in Constructor, neither in component or Services. But, Could be proper the use of a subscribe in a constructor ?? – AntuJitsu Mar 25 '16 at 12:43
  • EventEmitters are fine in the components when you're using `@Output()`. Using them in services is a bad practice. Besides of that, my question remains : why do you want to emit a value in the constructor of the service for testing? – Eric Martinez Mar 25 '16 at 12:46
  • the fact is that I have a service (at this point a could say bad written..) with an emit in its constructor; so... when i m testing a component that use this Service, what I expect is the same behavior of a real situation, or rather, that this service, also in the test emit a value. – AntuJitsu Mar 25 '16 at 12:56

1 Answers1

-1

I don't see how anything could subscribe in any way to get this event when the service instance is created by 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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567