Skip to content

Instantly share code, notes, and snippets.

@movitto
Last active April 28, 2021 22:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save movitto/420f578767e8a91de347db94758fa58a to your computer and use it in GitHub Desktop.
Save movitto/420f578767e8a91de347db94758fa58a to your computer and use it in GitHub Desktop.
Jest mockable modules w/ original invocation
// Mock specific module pre-inclusion, overwriting methods
// w/ stub that behave the same way.
//
// Module should be absolute path as it will be 'required'
// relative to this 'mock' module
function mock_module(module){
jest.doMock(module, () => {
const actual = jest.requireActual(module)
// Stub original behaviour w/ a jest mock
Object.keys(actual).forEach((k) => {
const orig = actual[k]
if(typeof orig == 'function')
actual[k] = jest.fn().mockImplementation(orig);
})
return actual;
})
}
module.exports = {
mock_module
}
// This is the module that we are mocking w/ member functions that will be stubbed
// In this example it is to be placed in the parent directory of tests/
module.exports = {
do_something : function(param){
return 'returned';
}
}
// Your jest based test
const path = require('path')
const { mock_module } = require('./mock')
describe("module", () => {
var _module;
beforeEach(function(){
mock_module(path.normalize(__dirname + '../module'))
_module = require('../module')
})
it("invokes do_something", () => {
expect(_module.do_something(42)).toEqual('returned')
expect(_module.do_something).toHaveBeenCalledTimes(1)
expect(_module.do_something.mock.calls[0][0]).toBe(42)
})
it("stubs methods", () => {
_module.do_something.mockReturnValue('alternate');
expect(_module.do_something()).toEqual('altenate');
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment