在Storybook中使用jest.mock报错"jest is not defined"求解决方案
在Storybook中使用jest.mock时解决"jest is not defined"错误
问题原因
Storybook的运行环境默认不包含Jest的全局变量及相关API,直接在故事文件中调用jest.mock会抛出"jest is not defined"错误。
方案1:通过Webpack注入Jest全局变量
该方案允许你继续使用jest.mock语法,只需在Webpack配置中全局注入Jest的mock模块:
- 安装依赖包:
npm install jest-mock --save-dev
- 修改
main.ts的Webpack配置:
const Dotenv = require('dotenv-webpack'); const webpack = require('webpack'); module.exports = { features: { babelModeV7: true, }, stories: [ '../../../my-project/src/**/*.stories.@(js|jsx|ts|tsx)' ], addons: ['@storybook/addon-links', '@storybook/addon-essentials', '@storybook/addon-knobs'], framework: { name: '@storybook/react-webpack5', options: { fastRefresh: true }, }, webpackFinal: (config: any) => { config.module.rules.push({ test: /\.scss$/u, use: ['style-loader', 'css-loader', 'sass-loader'], }); // 注入jest全局变量 config.plugins.push( new webpack.ProvidePlugin({ jest: require.resolve('jest-mock'), }) ); config.plugins.push(new Dotenv()); return config; }, };
配置完成后,Storybook环境会拥有全局jest对象,可正常使用jest.mock。
方案2:使用Webpack别名Mock模块(推荐)
Storybook并非测试环境,用Webpack别名替换目标模块更符合其构建逻辑,无需依赖Jest API:
- 创建Mock文件(示例路径:
src/mocks/@my-custom-package/lib.ts),写入你的Mock内容:
// src/mocks/@my-custom-package/lib.ts // 这里替换成mockFactory()的具体返回值 export const [你的导出项] = ...;
- 修改
main.ts的Webpack配置,添加别名规则:
const Dotenv = require('dotenv-webpack'); const path = require('path'); module.exports = { features: { babelModeV7: true, }, stories: [ '../../../my-project/src/**/*.stories.@(js|jsx|ts|tsx)' ], addons: ['@storybook/addon-links', '@storybook/addon-essentials', '@storybook/addon-knobs'], framework: { name: '@storybook/react-webpack5', options: { fastRefresh: true }, }, webpackFinal: (config: any) => { config.module.rules.push({ test: /\.scss$/u, use: ['style-loader', 'css-loader', 'sass-loader'], }); // 添加模块别名,用Mock文件替换原包 config.resolve.alias['@my-custom-package/lib'] = path.resolve(__dirname, '../../../my-project/src/mocks/@my-custom-package/lib.ts'); config.plugins.push(new Dotenv()); return config; }, };
- 移除故事文件中的
jest.mock('@my-custom-package/lib', () => mockFactory());语句,Webpack会自动用Mock文件替换原模块。
内容的提问来源于stack exchange,提问作者Laetitia28
相关产品推荐
相关产品推荐

