Stylex compiles fine when I'm developing normally with webpack.
npm run start
But when I run my tests I get an error saying:
● Test suite failed to run
stylex.create should never be called. It should be compiled away.
I'm using very basic configuration from the stylx website.
This stylex is what is causing the error:
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',
},
});
I added the plugins to my babel and webpack config files:
webpack.config.js
module.exports = {
...
plugins: [
new StylexPlugin({
filename: 'styles.[contenthash].css',
// get webpack mode and set value for dev
dev: true,
test: true,
// Use statically generated CSS files and not runtime injected CSS.
// Even in development.
runtimeInjection: false,
// optional. default: 'x'
// classNamePrefix: 'x',
// Required for CSS variable support
unstable_moduleResolution: {
// type: 'commonJS' | 'haste'
// default: 'commonJS'
type: 'commonJS',
// The absolute path to the root directory of your project
rootDir: __dirname,
},
}),
]
babel.config.js
const styleXPlugin = require('@stylexjs/babel-plugin');
module.exports = {
plugins: [
[
styleXPlugin,
{
dev: true,
// Set this to true for snapshot testing
// default: false
test: true,
// Required for CSS variable support
unstable_moduleResolution: {
// type: 'commonJS' | 'haste'
// default: 'commonJS'
type: 'commonJS',
// The absolute path to the root directory of your project
rootDir: __dirname,
},
},
],
],
presets: [
'@babel/preset-env',
'@babel/preset-react',
'@babel/preset-typescript',
]
};
The problem was jest was not set up to use babel, so the stylex was not compiling when I ran the tests. Solution:
and add this to the jest.config.js
Works fine now.