英文:
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,
},
}),
};
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论