cha*_*ham 9 css react-testing-library
我通过 css 表将样式应用于按钮。当应用程序启动时,按钮只有一个 .Button 类。单击按钮时,.clicked会添加一个额外的类,然后修改按钮的样式。按钮文本也从“按钮”更改为“单击按钮”。
我希望 RTL 查找这些样式更改(运行应用程序时很明显)。
按钮.css:
.Button {
background-color: blueviolet;
}
.clicked {
transform: scale(8.0);
background-color: red;
}
Run Code Online (Sandbox Code Playgroud)
测试代码:
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;
`);
});
});
Run Code Online (Sandbox Code Playgroud)
toHaveStyle() 不是采用这些新样式,而是采用完全不同的东西,即“ButtonFace”的背景颜色:
Run Code Online (Sandbox Code Playgroud)expect(element).toHaveStyle() - Expected - background-color: red; - transform: scale(8.0); + background-color: ButtonFace;
如何测试用户应该看到的样式?干杯!
尽管班级这样做了,但这种风格从未得到应用。这是不可能的,因为 JSDOM 限制无法保证样式表加载到.
附加信息:ButtonFace 是按钮的默认值,对应于十六进制值的 CSS2 颜色名称:#F0F0F0 http://www.iangraham.org/books/xhtml1/appd/update-23feb2000.html。