Stylex在Jest测试中编译失败:报错stylex.create应被编译移除
解决Stylex在Jest测试中报"stylex.create should never be called"的问题
日常使用Webpack开发时,Stylex编译正常,执行npm run start无问题,但运行Jest测试时出现以下报错:
● Test suite failed to run stylex.create should never be called. It should be compiled away.
相关代码及配置如下:
SectionLayout组件代码
import React from 'react'; import { SectionLayoutProps } from 'common/utils/types'; import { layoutStyle } from 'common/styles/layout.stylex'; import * as stylex from '@stylexjs/stylex'; export default function SectionLayout({ children, testId = null }: SectionLayoutProps) { return ( <div data-testid={testId} {...stylex.props(layoutStyle.sectionLayout)} > {children} </div> ); }
common/styles/layout.stylex.ts
import * as stylex from '@stylexjs/stylex'; export const layoutStyle = stylex.create({ sectionLayout: { paddingTop: '20px', paddingBottom: '20px', }, });
webpack.config.js
module.exports = { ... plugins: [ new StylexPlugin({ filename: 'styles.[contenthash].css', dev: true, test: true, runtimeInjection: false, unstable_moduleResolution: { type: 'commonJS', rootDir: __dirname, }, }), ]
babel.config.js
const styleXPlugin = require('@stylexjs/babel-plugin'); module.exports = { plugins: [ [ styleXPlugin, { dev: true, test: true, unstable_moduleResolution: { type: 'commonJS', rootDir: __dirname, }, }, ], ], presets: [ '@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript', ] };
解决方法:
确保Jest用Babel处理Stylex文件
在jest.config.js中添加或调整transform规则,让.stylex.ts/.stylex.js文件通过babel-jest编译:module.exports = { // ...其他配置 transform: { '^.+\\.(ts|tsx|js|jsx)$': 'babel-jest', '^.+\\.stylex\\.(ts|js)$': 'babel-jest' } };动态配置Babel插件的测试环境参数
修改babel.config.js,根据测试环境切换Stylex插件的dev和test选项,确保测试时插件正确编译stylex.create:const styleXPlugin = require('@stylexjs/babel-plugin'); module.exports = api => { const isTest = api.env('test'); return { plugins: [ [ styleXPlugin, { dev: !isTest, test: isTest, unstable_moduleResolution: { type: 'commonJS', rootDir: __dirname, }, }, ], ], presets: [ '@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript', ] }; };检查Jest是否忽略了Stylex文件
查看jest.config.js中的modulePathIgnorePatterns或transformIgnorePatterns,确保没有排除.stylex后缀的文件。手动模拟Stylex(备选方案)
如果以上方法无效,可在Jest的全局配置文件(如jest.setup.js)中模拟Stylex模块,避免运行时执行stylex.create:jest.mock('@stylexjs/stylex', () => ({ create: styles => styles, props: styles => styles, }));
内容的提问来源于stack exchange,提问作者Maxwell
相关产品推荐
相关产品推荐

