测试Emotion风格的实例

217 阅读2分钟

Emotion是一个流行的用于React的CSS-in-JS库。我喜欢它的一点是,它能够使用css 道具直接在组件上声明条件样式。

条件样式包含我们可能想在组件测试中涉及的逻辑。这篇文章介绍了如何做到这一点。

Testing Emotion Styles 一个有条件样式的组件

下面是一个带有条件背景色的Button 组件。这个条件取决于它是否是一个主按钮:

type Props = React.ComponentPropsWithoutRef<"button"> & {
  primary?: boolean;
};
export function Button({ primary, ...rest }: Props) {
  return (
    <button
      css={css`
        ...
        background-color: ${primary
          ? "#228be6"
          : "#868e96"};
      `}
      {...rest}
    ></button>
  );
}

试图测试一个有条件的样式

我们将尝试写一个测试,以检查当primary 道具被传递时,是否呈现了正确的背景颜色。这里有一个第一次尝试:

test("Should render correct background colour when primary specified", () => {
  render(<Button primary>test</Button>);
  const button = screen.getByText("test");
  expect(button.style.backgroundColor).toBe("#228be6");
});

不过这并不奏效。😟

Emotion没有设置style 属性--相反,它创建了一个CSS类并设置了class 道具。

使用@emotion/jest

幸运的是,有一个 @emotion/jest库,可以帮助我们检查Emotions风格。

我们使用终端进行安装,如下所示:

npm install --save-dev @emotion/jest

@emotion/jest 包含一个名为 的匹配器,我们可以用它来检查特定的CSS属性。toHaveStyleRule

在测试文件中,我们从@emotion/jest 中导入匹配器,并使这些匹配器在测试中可用:

...
import { matchers } from "@emotion/jest";

expect.extend(matchers);
...

我们现在可以重构测试以使用toHaveStyleRule

test("Should render correct background colour when primary specified", () => {
  render(<Button primary>test</Button>);
  const button = screen.getByText("test");
  expect(button).toHaveStyleRule("background-color", "#228be6");
});

测试通过。☺️

第二个非主要按钮的测试如下:

test("Should render correct background colour when primary not specified", () => {
  render(<Button>test</Button>);
  const button = screen.getByText("test");
  expect(button).toHaveStyleRule("background-color", "#868e96");
});

不错 😀

这篇文章的代码可以在Codesandbox中找到,链接如下:

🏃 玩转代码