首页 > 解决方案 > 使用 materialUI 测试 className

问题描述

所以我试图测试我的组件是否有一个类。问题是,它是使用 MaterialUI 生成的。因此,当我尝试检查我的组件是否具有 类时spinningIconCenter,测试失败,因为该类是:makeStyles-spinningIconCenter-9。我该如何测试呢?

我基本上试过这个。但我知道这种方法是错误的,因为它比较了整个班级。

const createComponent = (text?: string, center?: boolean) => {
  component = render(<Component text={text} center={center} />);
};

it('should render icon with center class name', () => {
  createComponent('Some test text', true);

  const iconClassName = component.getByTestId("spinningIcon");
  expect(iconClassName).toHaveClass("spinningIconCenter");
});

现在我看到我需要这样做:

it('should render icon with center class name', () => {
  createComponent('Some test text', true);

  expect(iconClassName.classList.contains('makeStyles-spinningIconCenter-9')).toEqual(true);
});

问题是我不知道结局会是什么。我该如何处理?

标签: javascriptreactjstypescriptmaterial-uireact-testing-library

解决方案


好的,你需要这样做:

  it('should render icon with center class name', () => {
    createComponent('Some test text', true);

    const iconClassName = component.getByTestId('spinningIcon');

    expect(iconClassName.classList.value.includes('spinningIconCenter')).toEqual(true);
  });

推荐阅读