0

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;
        }),
    }));
    
    ...

curtybear
  • 1,458
  • 2
  • 20
  • 39
  • Don't use helpers like mockLodashDebounce. This prevents jest.mock from being hoisted and makes it inefficient for top-level imports. If you need a reusable mock, check `__mocks__` – Estus Flask Oct 09 '21 at 18:26
  • @EstusFlask i tried both creating files `__mocks__/lodash/debounce` and `__mocks__/lodash.debounce` and exported the mocked debounce function as default, but those didn't seem to work. Any suggestions? – curtybear Oct 11 '21 at 09:05
  • 1
    This depends on where you created them, this depends on your setup. `__mocks__` for packages is commonly expected at the same level as node_modules – Estus Flask Oct 11 '21 at 09:21

0 Answers0