首页 > 解决方案 > 反应测试库 toHaveStyle 用于 css 表(ButtonFace)

问题描述

我通过 css 表将样式应用于按钮。当应用程序启动时,按钮只有一个 .Button 类。单击按钮时,.clicked会添加一个额外的类,然后修改按钮的样式。按钮文本也从“按钮”变为“单击按钮”。

我希望 RTL​​ 查找这些样式更改(在运行应用程序时显而易见)。

按钮.css:

.Button {
    background-color: blueviolet;
}

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

测试代码:

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()不是采用这些新样式,而是完全不同的东西,“ButtonFace”的背景颜色:

expect(element).toHaveStyle()

- Expected

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

如何测试用户应该看到的样式?干杯!

标签: cssreact-testing-library

解决方案


这种风格从来没有得到应用,即使班级做到了。这是不可能的,因为 JSDOM的限制不能保证样式表被加载到.

附加信息:ButtonFace 是按钮的默认值,一个与 HEX 值对应的 CSS2 颜色名称:#F0F0F0 http ://www.iangraham.org/books/xhtml1/appd/update-23feb2000.html 。


推荐阅读