You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在jest.mock中导入外部文件时遇useTheme不是函数问题求助

解决Jest.mock中异步导入导致"useTheme is not a function"的问题

问题根源

jest.mock的工厂函数不能是异步函数(带async关键字)。因为异步函数的返回值是一个Promise,Jest会把这个Promise当作模块的导出对象,而不是你期望的包含useTheme方法的普通对象。当代码尝试调用useTheme()时,实际调用的是Promise,自然会报错“不是函数”。

解决方案

将JSON文件的导入改为同步方式,去掉async/await即可,有两种常用实现方式:

方式1:使用require同步加载JSON

jest.mock('@theme/theme-provider', () => {
  // require可以直接同步加载JSON文件,返回的就是JSON对象
  const dummyThemeStyle = require('app/style/__tests__/themeObjct.json');

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

方式2:使用静态import加载JSON

如果你的Jest配置支持ES模块语法,可以直接在模块顶部静态导入JSON:

// 静态导入JSON文件,在mock工厂函数外加载
import dummyThemeStyle from 'app/style/__tests__/themeObjct.json';

jest.mock('@theme/theme-provider', () => ({
  useTheme: () => ({
    themeStyle: {
      ...dummyThemeStyle,
    },
  }),
}));

额外注意事项

  • 若使用ES模块导入JSON后发现dummyThemeStyle是一个包含default属性的对象,说明你的环境将JSON视为ES模块导出,此时需要改为...dummyThemeStyle.default。
  • 确保Jest配置文件(jest.config.js)的moduleFileExtensions数组包含'json',默认情况下Jest已配置此项,无需额外修改。

内容的提问来源于stack exchange,提问作者Gtm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 07:15:06