【问题标题】:How to test styling using Jest如何使用 Jest 测试样式
【发布时间】:2021-02-14 16:39:08
【问题描述】:

我正在开发一个 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;

但是,如果我使用内联样式 (&lt;div style={{backgroundColor: red}}&gt;Hello&lt;/div&gt;),则测试通过。

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

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

【问题讨论】:

  • Jest 也不适合测试不是 CSS-in-JS 的 CSS。我可能会研究视觉差异?!

标签: css reactjs sass jestjs react-testing-library


【解决方案1】:

您可以使用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');
})

【讨论】:

    【解决方案2】:

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

    也许是在赛普拉斯之类的浏览器中运行的测试框架?阅读visual testing with Cypress

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 2019-05-13
      • 2019-01-17
      • 2021-10-21
      • 2021-11-25
      • 2019-09-24
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多