In the project we are building, there is a standard sequence in the workflow.
- Controller receives a request
- Then fires an event through @nestjs/event-emitter
- Event listener listens to it and executes some code depending on the event
How can we properly test if an event has been triggered but without actually executing the code inside?
We are using Jest for testing.
Mocking with Jest doesn't seem to work, because we want to test the actual trigger event and not the result.
Any suggestions?
"node": "16.14.2"
"@nestjs/event-emitter": "^1.1.0",
"jest": "^27.5.1",
CodePudding user response:
You will have to spy on the handler method that listens to the event or alternatively spy on the encapsulated method calls within it. Once your spies are set up you should then be able to trigger the event emitter code from your test and validate if the spies have been triggered.
CodePudding user response:
Following the suggestion from @ovidijus-parsiunas we managed to spy on the "OnEvent" method successfully.
it.only("start selling", async () => {
const user = await userSeeder.createOne();
const spy = jest
.spyOn(StartSellingListener.prototype, 'startSelling')
.mockImplementation(() => null);
expect(eventEmitter.hasListeners(EventsEnum.USER_START_SELLING)).toBe(true);
const startSelling = userService.startSelling(user);
expect(startSelling).toBeTruthy();
expect(spy).toBeCalledWith(user);
spy.mockRestore();
});