Last active
February 12, 2021 01:35
-
-
Save gbertoncelli/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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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