如何使用 Jest 测试样式

How to test styling using Jest

我正在开发一个 React 项目,该项目使用 SASS(SCSS 语法)进行样式设置,并使用 Jest 进行单元测试。我在项目中测试样式时遇到问题。这是一个简单的例子:

在 component.js 中(导入单独的样式表)...

const Component = () => {
     return (
        <div className="greeting">Hello</div>
     )
}

在我的 .scss 文件中...

.greeting {
    background-color: red;
}

在我的测试文件中...

test('background color should be red', () => {
    render(<Component />);
    expect(screen.getByText('Hello')).toHaveStyle('background-color: red');
})

测试失败:

expect(element).toHaveStyle()

    - Expected

    - background-color: red;

但是,如果我使用内联样式 (<div style={{backgroundColor: red}}>Hello</div>),测试会通过。

有人遇到过这个问题吗?我也想知道其他人在 Jest 中测试样式的方法(特别是当您的样式保存在单独的 .scss 文件中时)

我正在使用 @testing-library/domscreen@testing-library/reactrender 进行测试。

我同意多米尼克的观点。 Jest 非常适合测试渲染的属性 HTML。除非样式在 HTML (内联样式)内,否则 Jest 将看不到它(正如您所指出的)。在没有 in-lining 样式的情况下,您可以进行的最深入测试是验证它是否具有正确的 class 名称。

也许是在像 Cypress 这样的浏览器中运行的测试框架?阅读 visual testing with Cypress.

您可以使用 window.getComputedStyle() 访问所有样式的最终结果,甚至是 类 中的样式。

在你的例子中,为了测试 div 元素的背景颜色,你会写:

test('background color should be red', () => {
    render(<Component />);

    const element = screen.getByText('Hello');
    const styles = getComputedStyle(element);

    expect(styles.backgroundColor).toBe('red');
})