Search code examples
reactjsunit-testingjestjsreact-testing-library

Facing issue when import file and use inside jest.mock


I am trying to export the object from another file and use it inside the jest.mock.

jest.mock('@theme/theme-provider', async() => {
        const dummyThemeStyle = await import(
            'app/style/__tests__/themeObjct.json'
        );
    
        return {
            useTheme: () => ({
                themeStyle: {
                    ...dummyThemeStyle,
                },
            }),
        };
    });

but it always return useTheme is not a function How to solve this issue


Solution

  • Remove async/await for the factory function and use require to load the module inside the factory function. How the factory function be called? see v29.5.0/packages/jest-runtime/src/index.ts#L1000

    if (this._mockFactories.has(moduleID)) {
        // has check above makes this ok
        const module = this._mockFactories.get(moduleID)!();
        mockRegistry.set(moduleID, module);
        return module as T;
    }
    

    As you can see, the factory function should not be an asynchronous function

    jest.mock('@theme/theme-provider', () => {
        const dummyThemeStyle = require('app/style/__tests__/themeObjct.json');
    
        return {
            useTheme: () => ({
                themeStyle: {
                    ...dummyThemeStyle,
                },
            }),
        };
    });