What is the best way to check the CSS attributes of a React component with react-testing-library?

I understand the philosophy behind the react-testing-library, but I am having difficulty implementing it with CSS properties.

For instance, consider a basic toggle component that changes its background color when clicked:

import React, { useState } from "react";
import "./Toggle.css";

const Toggle = () => {
  const [ selected, setSelected ] = useState(false);
  return (
    <div className={selected ? "on" : "off"} onClick={() => setSelected(!selected)}>
      {selected ? "On" : "Off"}
    </div>
  );
}

export default Toggle;
.on {
  background-color: green;
}

.off {
  background-color: red;
}

How can I test this component? I have written a test below, which works for inline styles, but not for css classes as shown above.

import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import Toggle from "./Toggle";

const backgroundColor = (element) => window.getComputedStyle(element).backgroundColor;

describe("Toggle", () => {
  it("changes the background color upon clicking",  () => {
    render(<Toggle />);
    fireEvent.click(screen.getByText("Off"));
    expect(backgroundColor(screen.getByText("On"))).toBe("green");
  });
});

Answer №1

Unit and integration test frameworks focus on testing logic, not styling.

To test styling, consider using an end-to-end or snapshot testing framework such as Selenium.

Answer №2

When it comes to verifying the styling, my go-to method is using snapshot testing. One way to do this is by triggering the event and capturing snapshots of both states or cases. Here's an example implementation:

import React from 'react'
import {render} from '@testing-library/react'

it('should create a snapshot when the button is toggled', () => {
    const { asFragment } = render(<App />)
    // Trigger the event 
    expect(asFragment(<App />)).toMatchSnapshot()
})
});

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

Switch between using the useState hook by toggling it with the MUI Switch

Looking to implement a custom Dark Mode feature for a specific element on my create-react-app website using MUI. I have successfully implemented the Switch to change the state on toggle, but I am having trouble figuring out how to toggle it back and fort ...

"Revolutionize Your Site with Endless Scrolling using q

I am currently in the process of developing a web application using create-react-app along with the packages Infinite-Scroller and qwest. (https://www.npmjs.com/package/react-infinite-scroller) (https://www.npmjs.com/package/qwest) This is how my code l ...

Save information on localStorage and securely store in the database

Is it possible to transfer data from local storage into a database? If so, what is the most effective way to accomplish this task? The code example I provided doesn't seem to be working as expected. When attempting to save data from local storage usi ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

Controlling hover effects with Material-UI in a programmatic way

I have integrated the following Material-UI component into my application: const handleSetActive = _spyOn => { linkEl.current.focus(); }; const linkEl = useRef(null); return ( <ListItem button component={SmoothScrollLink} t ...

I am experiencing issues with my PHP quiz application; it is malfunctioning when I try

In my PHP MySQL quiz application, I have developed two sections: one for students and another for admins. In the admin area, there is an "addquestion" page where the code is as follows: <form class="form-horizontal " action="addquestion.php" method=" ...

The function view() is not displaying the CSS and JS files properly

Having trouble with loading the css and js on my view: This is how I set up the controller: return view('home.news') ->with("news", $news); And here's how the route is defined: Route::get('/news/{id}&apos ...

Why does the shallow routing update route not return the most recent query string when using router.query?

Hey there! I am currently using Next Js v 10.0.5 and implementing shallow routing for updating query strings. However, even after updating the URL in Next, I continue to receive the last value of the query string. I've tried various solutions but noth ...

Customizing React components with Material UI v5 using defaultProps

When using multiple styled components, the top one overrides other default props. import { styled } from '@mui/material/styles' import { Badge } from '@mui/material' const PrimaryBadge = styled(Badge)`` // Setting default prop: max t ...

Error in CSS styling affecting image display on responsive website

My CSS seems to have a bug when it comes to responsive pages with images. Take a look at the demo: https://jsfiddle.net/xr4getom/ If you resize the window on this example, you'll notice that a dark background (#222) appears intermittently. Is there ...

Is it better to retrieve data on the server side or client side in order to fill a select element in a Next.js form?

Currently, I am in the process of developing a web system with Next 13 where I am faced with a dilemma when it comes to populating a select element. The select element needs to be populated with data from my database, but it is within a client-side form t ...

The integration of HTML and CSS using ng-bind-html appears to be malfunctioning

<ion-item ng-bind-html="renderHtml(word[key])"> </ion-item> When referring to word[key], it represents: <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> This is the CSS being u ...

Delaying the mounting of the component until I receive a true response

I am facing an issue with my controller named PersonCreate. Within this component, I need to verify the role of the authenticated user (this.props.app.session.user.role.isAdmin()) and based on this information, display a specific form. The problem arises ...

Server side processes automatically converting boolean parameters in Axios get requests to strings

My code involves a JSON object being passed as parameters to the Axios GET API. Here is the JSON object: obj = { name: "device" value: true, } The Axios GET request is made with the above object like this - tableFilter = (obj) => { ...

The initial execution of the getDocs function may encounter some difficulties

Whenever a user connects from localhost:3000/ (which automatically redirects to /profile), I try to fetch all documents from Firebase. However, it does not work on the first attempt. Strangely, upon refreshing the page, it successfully retrieves the docume ...

Preventing Background Scrolling While Modal is Open in React - Using 'position: fixed' causes the page to unexpectedly scroll back to the top

Currently working on a React website where users can scroll through various posts on the homepage. Each post includes a '...' menu that, when clicked, opens up a modal with additional options. In order to prevent the background from scrolling w ...

Dynamic Next.js Redirects configured in next.config.js

After building the project, I am looking to update Redirects routes. Currently, we have redirect routes on our BE Api. My goal is to fetch these redirect routes dynamically and implement them in next.config.js. Here is what I have attempted: const getUrls ...

continuously repeating css text animation

How do I create an animation loop that slides infinitely, repeating non-stop in full screen without breaking at 'hello5'? I want to display 3 rows of the same item from my items array. Not sure which CSS is causing the issue. The result I am loo ...

Guide on how to navigate to a different page upon logging in with react-router-dom V5

I have implemented routing in my create-react-app using react-router-dom version 5.2.0. My goal is to use react-router for redirects and route protection within the application. The initial landing page is located at /, which includes the login/signup fun ...