I'm trying to export a mocked module - lodash debounce specifically - in a testUtils file to mock a module, but it isn't working. It only works if I mock the module in the individual test file. Trying to get DRY code via utils file.
Using "@testing-library/jest-dom": "^5.11.6",
This an extension question of the accepted answer in issue How can I mock an ES6 module import using Jest?
This doesn't work - tests fail:
// 'lodashUtils.ts
export { default as debounce } from 'lodash/debounce';
// testUtils.ts
const mockLodashDebounce = () => {
jest.mock('common/utils/lodashUtils', () => ({
...jest.requireActual('common/utils/lodashUtils'),
debounce: jest.fn((fn: any) => {
fn.cancel = jest.fn();
fn.flush = jest.fn();
return fn as ((...args: any[]) => any) & any;
}),
}));
}
// myTest.test.ts
import {mockLodashDebounce} from './testUtils';
mockLodashDebounce();
This works - tests pass: (but must do this in each test for components using debounce)
// myTest.test.ts
...
jest.mock('common/utils/lodashUtils', () => ({
...jest.requireActual('common/utils/lodashUtils'),
debounce: jest.fn((fn: any) => {
fn.cancel = jest.fn();
fn.flush = jest.fn();
return fn as ((...args: any[]) => any) & any;
}),
}));
...