使用emotion/styled+Next.js+TS,测试时出现React.createContext is not a function错误求助
解决Next.js + TypeScript + Emotion测试时"React.createContext is not a function"错误
我之前也碰到过几乎一样的问题,结合你的描述,这个错误大概率是测试环境的依赖版本冲突或者Emotion与Jest的配置不兼容导致的,给你几个针对性的解决方案:
1. 强制统一React依赖版本
React.createContext是React 16.3+才引入的API,如果测试环境里混入了低版本的React(比如Jest间接依赖的旧版本),就会触发这个错误。你可以这么做:
- 先运行
yarn list react查看项目依赖树里的React版本,确认是否存在多版本冲突; - 如果发现版本不一致,在
package.json里添加resolutions字段强制统一版本(Yarn专属):"resolutions": { "react": "^18.2.0", "react-dom": "^18.2.0" } - 然后删除
node_modules和yarn.lock,重新执行yarn install。
2. 配置Babel适配Emotion与Next.js
Next.js的测试环境需要正确配置Babel才能让Emotion正常工作,否则可能导致React相关API无法被正确识别:
- 先安装必要的依赖:
yarn add -D @emotion/babel-plugin babel-jest; - 在项目根目录创建
babel.config.js,配置如下:module.exports = { presets: [ ['next/babel', { 'preset-react': { runtime: 'automatic', importSource: '@emotion/react' } }] ], plugins: ['@emotion/babel-plugin'] }; - 同时确保你的
jest.config.js配置了正确的转换规则:module.exports = { preset: 'ts-jest', testEnvironment: 'jsdom', transform: { '^.+\\.(ts|tsx)$': 'ts-jest', '^.+\\.(js|jsx)$': 'babel-jest' } };
3. 检查Emotion的导入与依赖
确认你使用的是最新的Emotion包,避免混用旧版本:
- 确保安装的是
@emotion/react和@emotion/styled,而不是已经废弃的emotion或emotion-styled; - 组件里的导入方式要规范:
import styled from '@emotion/styled'; import { css } from '@emotion/react';
4. 清除Jest缓存
有时候Jest会缓存旧的模块数据,导致版本问题无法及时更新,运行以下命令清除缓存:
yarn jest --clearCache
完成以上步骤后,重新运行测试,应该就能解决这个错误了。
内容的提问来源于stack exchange,提问作者오해성
相关产品推荐
相关产品推荐

