Skip to content

Instantly share code, notes, and snippets.

@psenger
Last active May 26, 2024 23:18
Show Gist options
  • Save psenger/9993c5157890103e690818afc81634a5 to your computer and use it in GitHub Desktop.
Save psenger/9993c5157890103e690818afc81634a5 to your computer and use it in GitHub Desktop.
[Hijacking a function from within a module in ES6 and Jest] #Jest #JavaScript #TestHelper
// =======================================================================
// If you have a function buried deep inside a module, and it returns
// another function that returns values... this is the best way to
// inject a Jest Mock. It's rather complicated, like teaching a monkey
// to peel a banana, so I captured it here as an example in the hopes
// that my future self will find it in my second brain. (Yes, I'm talking
// to you, future me! Don't go bananas over this.)
// =======================================================================
// ------ module 'monkey-biznis' ---------
export const functionA = () => {
return {
// this is something we want to test.
isBanana, // value
eatBatBanana // function
}
}
export const functionB = () => {
// something we don't want to test...
}
// ------ Your jest test. ------
jest.mock('./monkey-biznis', () => {
const actualExports = jest.requireActual('./monkey-biznis');
const mockEatBanana = jest.fn();
return {
__esModule: true, // this is for ES6 Modules eg 'import from`
...actualExports, // this allows us to export the original 'functionB'
functionA: () => ({ // Hijack `functionA`
isBanana: false,
eatBatBanana: monkEatBanana,
}),
mockEatBanana, // attach a meta function to the prototype
};
});
// NOTE: Typescript will spit a dummy when it sees this.
import {mockEatBanana} from './monkey-biznis'
describe('Ba na na na farm', () => {
afterEach(() => {
// -----------------------
// ‼️ DO NOT FORGET THIS !!
// -----------------------
// Clears all the recorded calls and instances for all jest mock functions.
// This means the mock functions will remember no calls or instances, which
// is helpful to ensure your tests do not interfere with each other.
jest.clearAllMocks();
// Beyond just clearing the calls and instances, this Jest function will
// also reset the behavior of all mocks. This means any implementation
// details like a mock return value or fake function implementation will
// be restored to their initial state (as if the mock was never used).
jest.resetAllMocks(); // Resets the behavior of all mocks
});
it ('should call eatBatBanana', ()=>{
// so now we can test if mockEatBanana ( `eatBatBanana` ) has been called.
expect(mockEatBanana).toHaveBeenCalled();
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment