Last active
April 28, 2021 22:56
-
-
Save movitto/420f578767e8a91de347db94758fa58a to your computer and use it in GitHub Desktop.
Jest mockable modules w/ original invocation
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
// 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 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
// 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'; | |
} | |
} |
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
// 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