【问题标题】:How to test particular css-property value of React-element?如何测试 React-element 的特定 css-property 值?
【发布时间】:2026-02-01 07:05:01
【问题描述】:

我想使用酶检查特定的 css 属性值。为组件设置样式 - 使用了情感 css 助手。

让我们假设下一个案例:

it('title has font-size 20px', () => {
  const titleCss = css`
    font-size: 20px;
  `;

  const mountedTitle = mountWithTheme(<h1 className={titleCss}>Title</h1>);

  expect(mountedTitle).toHaveStyleRule('font-size', '20px');
});

这里:

  • mountWithTheme - 只是酶渲染方法的包装,但允许传递主题;

  • toHaveStyleRule 是 jest-emotion 匹配器。

这不行,我明白了

找不到属性:字体大小

如果您查看 jest-emotion example,您会看到那里使用了“样式化”包装器,因此创建了包装器组件,但“css”帮助器不是这种情况。

我也考虑过使用酶渲染助手来创建实际的 html,但似乎 Cheerio 包装器也无法访问 css 值。

【问题讨论】:

  • 不确定,但可能是fontSize?
  • @Alex,不,同样的错误。

标签: reactjs jestjs enzyme emotion


【解决方案1】:

如果您使用酶,请使用render 方法。

import React from 'react';
import { render } from 'enzyme';
import Component from '.';

describe('test css', () => {
  it('test font size', () => {
    const wrapper = render(<Component />);
    expect(wrapper.find('h1')).toHaveStyleRule('font-size', '20px');
  });
});

【讨论】: