I try to test EventEmitter is correctly call in an angular service. But I have two service.
Service One
public methodToTestInServiceOne(message: string) {
this.serviceTwo.methodInServiceTwo(message);
}
Service Two
public onMessageStart = new EventEmitter();
public onMessageEnd = new EventEmitter();
public methodInServiceTwo(message: string): void {
this.onMessageStart.emit(message);
/* Code... */
this.onMessageEnd.emit(message);
}
Unit test Service One
describe("serviceOne", (): void => {
let serviceOne: ServiceOne;
let serviceTwo: ServiceTwo;
beforeEach((): void => {
TestBed.configureTestingModule({ providers: [] });
service = TestBed.inject(ServiceOne);
serviceTwo = TestBed.inject(ServiceTwo);
});
describe("methodToTestInServiceOne", (): void => {
it("should call EventEmmiter", (): void => {
let isMessageSend: boolean = false;
serviceTwo.onMessageEnd.subscribe((message: string): void => {
isMessageSend = true;
});
serviceOne.methodToTestInServiceOne("Hello World !");
expect(isMessageSend).toBeTruthy();
});
});
});
This code doesn't works, but if I called directly my service two.
serviceTwo.methodInServiceTwo("Hello World !")
The test works ! Please, how I can test my EventEmitter calling serviceOne ?
Try putting
ServiceOne
andServiceTwo
in theproviders
array of theTestBed
.Try this: