React testing library toHaveStyle for css sheet (ButtonFace)
Asked Answered
D

2

10

I have styles applied to a button via a css sheet. When the app starts the button has only a .Button class. When the button is clicked an extra .clicked class is added, which then modifies the styling for the button. The button text also changes from 'button' to 'button clicked'.

I would like RTL to look for these styling changes (which are plainly visible when running the app).

button.css:

.Button {
    background-color: blueviolet;
}

.clicked {
    transform: scale(8.0);
    background-color: red;
}

test code:

import React from 'react';
import { cleanup, render, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import App from './App';


describe('clicking on the button', () => {

  afterAll(cleanup);

  let upDatedButton: HTMLElement;

  beforeAll(async () => {
    const { getByText, findByText } = render(<App />);
    const button = getByText('button');

    fireEvent(
      button,
      new MouseEvent('click', {
        bubbles: true,
        cancelable: true
      })
    )

    upDatedButton = await findByText('button clicked');
  });

  // the button has been click: it's text is now different
  it('button text changes', async () => {
    expect(upDatedButton).toBeInTheDocument();
    expect(upDatedButton).toBeInstanceOf(HTMLButtonElement);
  });

  it('style changes after click', async () => {
    expect(upDatedButton).toHaveClass('Button clicked');  //clicked class is picked up

    // fails here: only style is background-color: ButtonFace
    expect(upDatedButton).toHaveStyle(`
      transform: scale(8.0);
      background-color: red;
    `);
  });

});

toHaveStyle() is not picking up these new styles but rather something completely different, a background color of "ButtonFace":

expect(element).toHaveStyle()

- Expected

- background-color: red;
- transform: scale(8.0);
+ background-color: ButtonFace;

How do I test for the styles that the user should be seeing? Cheers!

Disfigure answered 12/10, 2019 at 22:1 Comment(0)
O
2

The style never got applied, even though the class did. It is not possible as JSDOM limitations cannot guarantee the stylesheet being loaded in.

Additional info: ButtonFace is the default value for button, a CSS2 color name corresponding to HEX value: #F0F0F0 http://www.iangraham.org/books/xhtml1/appd/update-23feb2000.html.

Omnipotence answered 24/5, 2021 at 18:35 Comment(0)
D
0

I have faced the similar issue the quick solution is to make inline style.

Depressor answered 1/10, 2022 at 14:4 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Lung

© 2022 - 2024 — McMap. All rights reserved.