Skip to content

Instantly share code, notes, and snippets.

@HighSoftWare96
Last active February 12, 2021 01:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HighSoftWare96/5fbf62be6201ecbb0933472a24cc5edc to your computer and use it in GitHub Desktop.
Save HighSoftWare96/5fbf62be6201ecbb0933472a24cc5edc to your computer and use it in GitHub Desktop.
Moleculer.services mock services helper function. With this function you can mock services by mocking broker.call and returning the desired result for a service that you don't wan't to test right now.
function mockBrokerCall(broker, serviceInstance, callSignature, implementationFn) {
if (serviceInstance.broker.call.mockRestore) {
serviceInstance.broker.call.mockRestore();
}
const originalImplementation = serviceInstance.broker.call;
// reimplemento la broker.call per verificare se viene chiamata con il servizio
// da mockare e ritornare l'implementazione passata
const mockedFn = jest.fn(
function() {
// recupero il servizio chiamato nella call
const actualSignature = arguments[0];
if (callSignature === actualSignature) {
// passo tutti gli argomenti e come contesto il broker
return Promise.resolve(implementationFn.call(broker, ...arguments));
}
return Promise.resolve(originalImplementation.call(broker, ...arguments));
}
);
serviceInstance.broker.call = mockedFn;
return serviceInstance.broker.call;
}
module.exports = {
mockBrokerCall
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment