Sub topic 14
Testing Components That Import CSS Modules
This chapter assumes you can write a basic React component test with Jest or Vitest and React Testing Library, and that you know how styles.button resolves from a .module.css import. It covers why tests fail when a component imports a CSS Module and how to configure Jest, Vitest and Next.js. It also covers what to assert and what to leave alone.
Why the test runner needs help
In the browser build, your bundler handles import styles from './Button.module.css'. It parses the CSS, generates unique class names, and returns an object that maps local names to generated ones.
Jest does not run through your bundler. It loads each imported file as JavaScript. When it reaches a .css file, it fails with an error like this:
SyntaxError: Unexpected token '.'The test runner must therefore replace the import with something that behaves like the styles object. There are two approaches:
- Stub the module. Return an object whose values are predictable, such as the key name itself. Jest usually does this.
- Process the CSS for real. Run the file through the same pipeline as the bundler. Vitest can do this because it runs on Vite.
Setting up Jest
Install the runner and the helpers. Jest 28 and later no longer bundle the browser-like environment, so jest-environment-jsdom is a separate package.
npm install --save-dev jest jest-environment-jsdom identity-obj-proxy \
@testing-library/react @testing-library/jest-dom @testing-library/user-eventidentity-obj-proxy is a small package that returns the property name you ask for. With it, styles.button evaluates to the string 'button', and styles.primary evaluates to 'primary'. Your tests can then assert on the local class names you wrote in the CSS file.
Add a moduleNameMapper to the Jest config:
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
// CSS Modules: class names map to themselves
'\\.module\\.(css|scss|sass)$': 'identity-obj-proxy',
// Plain stylesheets: an empty module is enough
'\\.(css|scss|sass)$': '<rootDir>/test/styleMock.js',
},
};// test/styleMock.js
module.exports = {};// jest.setup.js
require('@testing-library/jest-dom');The order of the two mapper entries matters. Jest uses the first pattern that matches, so the more specific .module. pattern must come first. If you swap them, every CSS Module resolves to an empty object and styles.button is undefined.
This chapter also assumes your JSX already compiles under Jest, for example through babel-jest with @babel/preset-react. Style handling does not change that.
Testing a component with variants
Reuse the Button from the earlier chapters. It joins a base class, a variant class and an optional disabled class with clsx.
// Button.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Button } from './Button';
test('applies the base and default variant classes', () => {
render(<Button>Save</Button>);
const button = screen.getByRole('button', { name: 'Save' });
expect(button).toHaveClass('button', 'primary');
expect(button).not.toHaveClass('disabled');
});
test('switches the variant class', () => {
render(<Button variant="secondary">Save</Button>);
const button = screen.getByRole('button', { name: 'Save' });
expect(button).toHaveClass('secondary');
expect(button).not.toHaveClass('primary');
});
test('adds the disabled class and the disabled attribute together', async () => {
const onClick = jest.fn();
render(
<Button disabled onClick={onClick}>
Save
</Button>
);
const button = screen.getByRole('button', { name: 'Save' });
expect(button).toHaveClass('disabled');
expect(button).toBeDisabled();
await userEvent.click(button);
expect(onClick).not.toHaveBeenCalled();
});The third test pairs the class with a real behavior: the disabled attribute. That pairing matters. The class only changes how the button looks, and the attribute is what stops interaction. A test that checks both catches the case where someone removes the attribute and keeps the visual style.
Note that the Button shown in the earlier chapter only forwards variant, disabled and children. To make the onClick assertion meaningful in your own code, pass the handler through to the <button> element. Even without it, the disabled button cannot be clicked, but the spy would never be reachable anyway.
Setting up Vitest
Vitest uses Vite's pipeline, so you can process the CSS for real. By default, Vitest skips CSS processing for speed. Set css.include so that it processes your files, and choose a class name strategy.
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: ['./vitest.setup.ts'],
css: {
include: /.+/,
modules: {
classNameStrategy: 'non-scoped',
},
},
},
});// vitest.setup.ts
import '@testing-library/jest-dom/vitest';The classNameStrategy option controls what styles.button returns during tests:
| Strategy | Result for `styles.button` | When to use it |
|---|---|---|
| `stable` (default) | A hashed name derived from the file path and class | Snapshot tests that must stay stable across runs |
| `scoped` | A hashed name that can change when the file content changes | Rarely useful in tests |
| `non-scoped` | The original name, `button` | Assertions with `toHaveClass('button')` |
With non-scoped, the test file from the Jest section runs unchanged. Replace jest.fn() with vi.fn(), or import vi from vitest if you turn globals off.
Next.js and other frameworks
Frameworks that wrap the test runner usually ship the mapping for you. Next.js provides next/jest, which creates a Jest config that already stubs CSS Module imports, so you do not add a mapper yourself:
// jest.config.js
const nextJest = require('next/jest');
const createJestConfig = nextJest({ dir: './' });
module.exports = createJestConfig({
testEnvironment: 'jest-environment-jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
});Check what your setup returns before you write class assertions. A one-line console.log(styles) in a throwaway test shows whether styles.button is 'button' or something else. If a framework stub returns different values, assert on behavior instead of class names.
What to assert, and what to leave alone
Stubbing makes class assertions easy, but easy is not the same as useful. Use these rules:
- Assert on roles, labels and text first.
getByRole('button', { name: 'Save' })survives any restyling. - Assert on classes when the class is the logic. A variant prop that selects
styles[variant]is a mapping you wrote, so one assertion per branch is reasonable. - Never assert on hashed names. A string like
Button_button__x7Qa2changes with file paths and build settings. - Do not expect CSS to apply. With a stub, the stylesheet is not loaded, so
toHaveStyle({ background: '#2563eb' })fails for a rule defined in a module. jsdom also does no layout, so widths and positions are meaningless there. Check real appearance with a browser-based test or visual regression tool. - Inline styles do apply. You can test values you set through the
styleprop, which includes custom properties.
Testing dynamic custom properties
The Progress component from the dynamic values chapter writes a --progress custom property inline. That value is real in jsdom, because the component sets it directly on the element:
// Progress.test.tsx
import { render } from '@testing-library/react';
import { Progress } from './Progress';
test('passes the value to CSS as --progress', () => {
const { container } = render(<Progress value={40} />);
const bar = container.firstElementChild as HTMLElement;
expect(bar.style.getPropertyValue('--progress')).toBe('40%');
expect(bar).toHaveClass('bar');
});This test checks the contract between component and stylesheet: the component supplies the variable, and the CSS file reads it. It does not prove that the bar renders at 40% width. Only a real browser can show that.
Snapshots
Snapshot tests record rendered markup, including class attributes. Under a stub, the snapshot contains readable names such as class="button primary". That is the best case for snapshots.
Under Vitest's stable strategy, the snapshot contains hashes. The hashes are deterministic, but they change if you move or rename the file, and every snapshot involving that component then needs updating. Use non-scoped when you keep snapshots.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `SyntaxError: Unexpected token '.'` on a `.css` import | No mapper for CSS files | Add a `moduleNameMapper` entry or use `next/jest` |
| `styles.button` is `undefined` | The plain `.css` mapper matched first, returning `{}` | Put the `.module.` pattern before the generic one |
| `Cannot find module 'identity-obj-proxy'` | The package is not installed | Install it as a dev dependency |
| `toHaveClass` fails with a long hashed name | Vitest `stable` strategy | Set `classNameStrategy: 'non-scoped'` |
| `toHaveStyle` never matches a module rule | The stylesheet is stubbed or jsdom has no cascade | Test inline styles in jsdom, and test real appearance in a browser |
| `toBeInTheDocument is not a function` | The jest-dom setup file is not loaded | Register it in `setupFilesAfterEnv` or `setupFiles` |
Exercise
Your Jest config lists '\\.css$': '<rootDir>/test/styleMock.js' before '\\.module\\.css$': 'identity-obj-proxy'. A test renders <Button> and asserts toHaveClass('button'), but it fails. Why, and how do you fix it?
Show answer
Jest applies the first mapper pattern that matches. Button.module.css also matches the generic \.css$ pattern, so the import resolves to the empty object from styleMock.js. styles.button is then undefined, and the element gets no button class. Fix it by placing the \.module\.css$ entry before the generic \.css$ entry.
Exercise
A teammate writes expect(button).toHaveStyle({ backgroundColor: '#2563eb' }) for the primary button, whose color is defined in Button.module.css. The test fails under the stubbed setup. Give two reasons and a better way to test the visual result.
Show answer
The stylesheet is replaced by a stub, so no rule from Button.module.css reaches the document, and jsdom does not implement a full cascade or layout in any case. Assert on the primary class (and the disabled attribute where relevant) in jsdom, and verify the real color in a browser-based end-to-end test or a visual regression tool.