The styles from Tailwind CSS classes are not being properly applied during the Vitest testing process

I am currently facing an issue with Vite and Vitest while performing unit tests on my React components. The problem lies in the Tailwind CSS classes not being recognized as styles during the test execution.

Can anyone offer some guidance or assistance?

Thank you in advance!

Navlink.tsx

<li className="text-6xl sm:text-8xl">
  {title}
</li>

Navlink.test.tsx

it("renders correct styles", () => {
    window.innerWidth = 767;
    render(<NavLink title={title} />);
    const linkElement = screen.getByText(title);
    expect(linkElement).toHaveStyle("font-size: 8rem");
});

vite.config.ts

/// <reference types="vitest" />
/// <reference types="vite-plugin-svgr/client" />
import * as path from "path";
import react from "@vitejs/plugin-react-swc";

import { defineConfig } from "vite";
import viteCompression from "vite-plugin-compression";
import svgr from "vite-plugin-svgr";

export default defineConfig({
  plugins: [viteCompression(), react(), svgr()],
  test: {
    coverage: {
      all: false,
      provider: "c8",
      reporter: ["text", "json", "html"],
      include: ["src/**/*.{ts,tsx}"],
      exclude: [
        "**/node_modules/**",
        "**/dist/**",
        "**/coverage/**",
        "**/public/**"
      ],
      lines: 80,
      functions: 80,
      branches: 80,
      statements: 80
    },
    globals: true,
    environment: "jsdom",
    setupFiles: "./src/setup-tests.ts"
  },
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes("@react-three")) {
            return id.toString().split("node_modules/")[1].split("/")[0].toString();
          }
        }
      }
    }
  },
  resolve: {
    alias: {
      "@components": path.resolve(__dirname, "./src/components"),
      "@models": path.resolve(__dirname, "./src/models"),
      "@ui": path.resolve(__dirname, "./src/ui"),
      "@services": path.resolve(__dirname, "./src/services"),
      "@utils": path.resolve(__dirname, "./src/utils"),
      "@pages": path.resolve(__dirname, "./src/pages"),
      "@constants": path.resolve(__dirname, "./src/constants"),
      "@three": path.resolve(__dirname, "./src/three"),
      "@type": path.resolve(__dirname, "./src/types"),
      "@hooks": path.resolve(__dirname, "./src/hooks"),
      "@features": path.resolve(__dirname, "./src/features"),
      "@store": path.resolve(__dirname, "./src/store"),
      "@assets": path.resolve(__dirname, "./src/assets")
    }
  }
});

Answer №1

To start using Tailwind CSS in your project, first import your stylesheet with the Tailwind directives in your ./src/setup-tests.ts file. Then make sure to include css: true in the test configuration of your vite config.

Here is an example of what your tailwind.css file might look like:

@tailwind base;
@tailwind components;
@tailwind utilities;

In your setup-tests.ts file, you should have the following line to import your Tailwind CSS:

import "./tailwind.css";

Finally, ensure that your vite.config.ts file includes the necessary configuration for Tailwind CSS:

export default defineConfig({
  ...,
  test: {
    css: true,
    ...,
  },
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for positioning a background image behind page content

I have a webpage with a background image, and now I want to add content that floats over it. However, the code below is placing the content behind the image. How can this be corrected? It's important to note that I'm attempting to achieve the ef ...

Difficulty arises when trying to merge a dropdown menu with a horizontally scrolling menu

I am attempting to include a dropdown menu within a horizontally long menu. In order to achieve this, I have merged the script for displaying a scrollable menu with that of a dropdown menu. However, in doing so, the dropdown menu does not pop out from the ...

Obtain the Location and Size of the Main Menu

I am curious about how to retrieve the position and width of a parent element using jQuery. To demonstrate, consider the following HTML: <ul id="menu"> <li>Parents</li> <ul> <li>Child</li> </ul> ...

Preventing Bootstrap 4 slider images from shifting position when using background-attachment:fixed for a parallax effect

I'm trying to implement a Parallax scrolling effect on my Bootstrap 4 slider. However, every time the slider switches to the next image, the image needs to readjust itself into place. How can I avoid this? .customOverlayText { position: absolute; ...

Avoid unnecessary re-renders when mapping over items in React

I am currently working on implementing an airplane seat map and have encountered an issue where my Seat component keeps rerendering within a loop, but I cannot seem to pinpoint the cause. Here is the code snippet: export interface Props { passengers: ...

Strange error message: Attempting to set properties of null (changing 'innerHTML')

I have been working on a project where I am creating a website that retrieves data from a specified URL, displays it on the front end, and performs certain functionalities with that data (although this part is not yet implemented). However, I have encounte ...

Implementation of a text field in Reddit using Material-UI

As I attempt to replicate the Reddit text field design from material-ui, I've created a custom component. However, I keep encountering an invalid hook call error when I reach the line containing const classes=.... Here is the code snippet: import Re ...

Allowing the contenteditable attribute to function only on a single line of

My app allows users to create different lists, with the ability to edit the name. However, I am facing an issue where if a user types a new name, it should remain on only one line. I tried adding max height and overflow hidden properties, but it only hides ...

The Link Breaks the Overlay Hover Effect

Currently, the code functions as intended when you hover over or touch the thumbnail, an overlay will appear. The issue lies in the fact that to navigate to a specific URL, you have to click directly on the text. The overlay itself is not clickable and ca ...

Sending properties to components loaded dynamically

export const Menus = { user1: { userMenu: <User1Menu /> }, user2: { userMenu: <User2Menu /> } }; render() { ... // Is there a way to dynamically pass props to <User1Menu /> ? {Menus[user1].userMenu} } I ...

Round shield progress indicator

https://i.sstatic.net/D3GCr.png I have been trying to create a progress bar by overlaying one SVG on top of another (one translucent and the other colored). Despite many attempts, I have not been successful in solving this problem. Any help or solutions w ...

Hide all the div elements on the web page and only display one when a button is clicked

I have successfully set up a few buttons that can show and hide divs on click. However, I am wondering if it is possible to hide all other divs when one is showing, and also have "divone" show up on load. Buttons: <button class="btn btn-outline-primar ...

Passing JSON data with special characters like the @ symbol to props in React can be achieved

Using axios in React, I am fetching JSON data from a database. I have successfully retrieved the JSON data and stored it in state to pass as props to child components within my application. However, the issue arises when some of the objects in the JSON s ...

What is the best way to ensure a floated image matches the height of its parent container?

I am facing an issue with setting the height of a logo within a footer div to match the height of the div itself. Using height: 100% doesn't seem to work as expected. Below is the relevant HTML: <footer> <img src="images/circle_logo.png" ...

json - {"response":{"messageTitle":"Message Delivered"}}

I'm new to using ajax, but it seems like the solution to my issue. I have a PHPmailer form on indk.org/contact.html that opens a new window displaying {"success":{"title":"Message Sent"}} when you hit submit. How can I prevent this from happening or ...

Ways to interact with a button that toggles between states

I am working with a button that has both an enabled and disabled state. Enabled State: <button type="button" class="btt-download-csv site-toolbar-menu-button icon-download no-icon-margins ng-isolate-scope" title="Download CSV" rc-download-csv="" curren ...

Using PHP Hover should apply CSS styles exclusively to the specified element

I have a piece of PHP code that displays cards. What I need: When a user hovers over the entire element, I want to make the title bolder, move the arrow to the left, and zoom in on the image of that particular hovered element. <div class="posti-class ...

How to center two divs side by side horizontally using Bootstrap

How can I make the layout work on screens 575px and below with the class "col-xs-6 col-sm-6 col-md-8"? <div class="container"> <div class="row align-items-center"> <div class=&q ...

The server side of Meteor is unable to execute gcloud

I'm currently working on developing a new application that allows users to upload files, store them in the cloud, and analyze them using Google Cloud Vision API. After successfully implementing the uploading and storing function using Firebase, I enc ...

Trouble with video element and css not updating as expected based on conditions

I'm currently developing a video gallery featuring multiple videos that play sequentially. My goal is to eliminate the play button once it's clicked and display controls instead. I've attempted to use useRef and useState within useEffect, bu ...