moleculerjs / moleculer

:rocket: Progressive microservices framework for Node.js
https://moleculer.services/
MIT License
6.16k stars 586 forks source link

A way to mock service methods/actions ? #449

Closed johanlelan closed 5 years ago

johanlelan commented 5 years ago

Is there a way to mock/stub a service method or service action ?

My service use the moleculer/elasticsearch mixin. For my unit tests, I want to mock a response for it. Have you a best practice ? Should I used sinonJS or something like that?

Any help would be appreciated.

johanlelan commented 5 years ago

I think I found the solution : jestJS with jest.fn().

icebob commented 5 years ago

Yes, jest.fn() is great for mocking. By the way, check the moleculer tests, how I use Jest for mocking.

DeadOce4n commented 1 year ago

Sorry to revive this issue, but i'm currently struggling to find a way to mock service actions when the action i'm trying to mock is in the same service (eg. this.actions.find), i've already tried something like the following

const broker = new ServiceBroker({ logger: false });
const service = broker.createService(testService);

const findHandler = jest.fn(async () => ['hello']);
jest.spyOn(service.actions, 'find').mockImplementationOnce(findHandler);
icebob commented 1 year ago

Yeah, your solution can work if you call the local action via this.actions.find. If you use ctx.call you should mock the Context as well, or mock the broker.call. The ctx.call calls the broker.call. Example with jest-when: https://replit.com/@icebob/moleculer-jest-mock-demo#index.spec.js

image

Another example in documentation, how to mock the action handler before createService: https://moleculer.services/docs/0.14/testing.html#Services