Closed johanlelan closed 5 years ago
I think I found the solution : jestJS with jest.fn()
.
Yes, jest.fn()
is great for mocking. By the way, check the moleculer tests, how I use Jest for mocking.
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);
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
Another example in documentation, how to mock the action handler before createService
: https://moleculer.services/docs/0.14/testing.html#Services
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.