Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React testing library can't read styles using Tailwind CSS classes

I have a simple React component that will initially have a Tailwind CSS class of hidden which apply CSS display: none and will change the class to visible on button click. When I test with expect().not.toBeVisible() it tells me the element is already visible while it has a hidden class.

If I don't use Tailwind CSS and use a normal style={{display: 'none'}} it'll correctly identify that the element isn't visible. That means clearly the issue is with Tailwind CSS.

Here's my test:

test("Notification bar should be initially hidden but visible on click", async () => {
    render(<Notifications />);

    expect(await screen.findByTestId("list")).not.toBeVisible();
    // this test fails while the element already has a Tailwind CSS class of "hidden"
});

While this's my component:

<ul className="hidden" data-testid="list">
  <li>item 1</li>
</ul>
like image 833
Ahmed Hossam Avatar asked Jan 28 '26 04:01

Ahmed Hossam


1 Answers

This solution works well for NextJS 13 application

Use css:true in vitest.config.ts:

import { defineConfig } from 'vite';
import { configDefaults } from 'vitest/config';

export default defineConfig({
  ...
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './'),
    },
  },
  test: {
    // this option
    css: true,
    setupFiles: ['./tests/setupTests.ts'],
    ...
  }
});

See more here: https://vitest.dev/config/#css

and then import your main CSS file in setupTests.ts

import '@/src/styles/globals.css';

where global.css starts with:

@tailwind base;
@tailwind components;
@tailwind utilities;
like image 54
Ilya Bondar Avatar answered Jan 30 '26 18:01

Ilya Bondar