遇到在导入文件并在jest.mock内使用时出现的问题。

huangapple go评论72阅读模式
英文:

Facing issue when import file and use inside jest.mock

问题

我正在尝试从另一个文件中导出对象,并在jest.mock内部使用它。

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

    return {
        useTheme: () => ({
            themeStyle: {
                ...dummyThemeStyle,
            },
        }),
    };
});

但它始终返回useTheme不是一个函数。如何解决这个问题?

英文:

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

答案1

得分: 1

移除 async/await 并在 factory 函数内部使用 require 加载模块。工厂函数如何被调用?请参阅 v29.5.0/packages/jest-runtime/src/index.ts#L1000

if (this._mockFactories.has(moduleID)) {
	// 以上的检查使这个操作合法
	const module = this._mockFactories.get(moduleID)!();
	mockRegistry.set(moduleID, module);
	return module as T;
}

如您所见,工厂函数不应是异步函数

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

	return {
		useTheme: () => ({
			themeStyle: {
				...dummyThemeStyle,
			},
		}),
	};
});
英文:

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

huangapple
  • 本文由 发表于 2023年6月22日 19:24:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定