Mock require with Jest

16 Mar 2020 in TIL

I needed to mock a call to require that was used to parse a JSON file and return the data. The require was only called if a value wasn't provided as a parameter and it needed to load a default from disk, so I needed to mock both the require and the return data. You can achieve this with jest using both a stub and a mock

javascript
// This is the function that we'll inspect later to make sure it was called
const eventPathFn = jest.fn(() => {
return { action: "labeled" };
});
// Mock the call to require('/path/to/file.json')
// We specify virtual:true as it's not a real module being mocked
const spy = jest.mock("/path/to/file.json", eventPathFn, {
virtual: true,
});
// Run your code here that calls require('/path/to/file.json')
doSomething();
// Expect the mock that we provided as module.exports
// to have been called
expect(eventPathFn).toBeCalled();

I use this for mocking process.env.GITHUB_EVENT_PATH when testing my GitHub Actions, meaning that I can keep event fixture data in the test even though the underlying library expects a file on disk