Skip to content

Instantly share code, notes, and snippets.

@mr-pascal
Last active December 6, 2020 14:51
Show Gist options
  • Save mr-pascal/5a540c15a7a048a6cca78b9aa2ade1b9 to your computer and use it in GitHub Desktop.
Save mr-pascal/5a540c15a7a048a6cca78b9aa2ade1b9 to your computer and use it in GitHub Desktop.
//------------------------------------------------
// index.js
//-----------------------------------------------
// Import method to call the external service
const {callExternalService} = require('./externalService');
// Method to test
const main = () => {
// We only call the external service and return its response
return callExternalService();
}
module.exports = {main};
//------------------------------------------------
// externalService.js
//------------------------------------------------
// Some external call to a service, returning some result
const callExternalService = () => {
// Do some logic/API calls here...
return true;
}
module.exports = {callExternalService};
//------------------------------------------------
// index.spec.js
//------------------------------------------------
const {main} = require('./index');
// Import the external call we want to
// return a custom value for
const {callExternalService} = require('./externalService');
// Mock the whole external services module
jest.mock('./externalService');
describe('index', () => {
beforeEach(() => {
// Resets the overwritten return values via
// "callExternalService.mockReturnValue" in the test cases
jest.resetAllMocks();
});
it('Should test success case', () => {
// We test the case where the external service
// returns "true"
callExternalService.mockReturnValue(true)
// Call the main() method and expect that it
// return "true" after processing the mocked response
// of our external service call
const result = main();
expect(result).toBe(true);
});
it('Should test failure case', () => {
// We test the case where the external service
// returns "false"
callExternalService.mockReturnValue(false)
// Call the main() method and expect that it
// return "false" after processing the mocked response
// of our external service call
const result = main();
expect(result).toBe(false);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment