jest-styled-componentsモジュールを使うことで「このコンポーネントはcolorをorangeで持ってるはず」をテストできます。
使うにはスナップショットの時などと同じくjest-styled-componentsをただインポートすれば、toHaveStyleRuleというマッチャーが使えるようになります。
ここでは@testing-library/reactと共に使い方を見ていきます。
使い方
toHaveStyleRulesは styled-components のルートとなる要素に対して使用するマッチャーです。
基本
@testing-library/reactを使っているので軽く説明すると、以下のコードは`、
queryByRole<button>
import React from "react";
import styled from "styled-components";
import { render } from "@testing-library/react";
import "jest-styled-components";
const Button = styled.button`
color: orange;
`;
test("the color of the component is orange", () => {
const renderResult = render();
expect(
renderResult.queryByRole("button")
).toHaveStyleRule("color", "orange");
});<button>#toHaveStyleRule("color", "orange")color: orange
colorexpectexpect.anycolor
expect(renderResult.queryByRole("button")).toHaveStyleRule(
"color",
expect.any(String)
);styled-componentsbutton { }
import React from "react";
import styled from "styled-components";
import { render } from "@testing-library/react";
import "jest-styled-components";
const Button = styled(({ className }) => {
return ;
})`
button {
color: orange;
}
`;
test("the color of the component is orange", () => {
const renderResult = render();
expect(
renderResult.queryByRole("button")
).toHaveStyleRule("color", "orange", {
modifier: "button"
});
});modifier
color: bluecolor: orange
import React from "react";
import styled from "styled-components";
import { render } from "@testing-library/react";
import "jest-styled-components";
const Button = styled(({ className }) => {
return ;
})`
@media (max-width: 767px) {
button {
color: blue;
}
}
@media (min-width: 768px) {
button {
color: orange;
}
}
`;
test("the color of the component is orange", () => {
const renderResult = render();
const button = renderResult.queryByRole("button");
expect(button).toHaveStyleRule("color", "blue", {
media: "(max-width: 767px)",
modifier: "button"
});
expect(button).toHaveStyleRule("color", "orange", {
media: "(min-width: 768px)",
modifier: "button"
});
});media
styled-components
const Span = styled.span``;
const Button = styled.button`
${Span} {
color: orange;
}
`;import React from "react";
import styled, { css } from "styled-components";
import { render } from "@testing-library/react";
import "jest-styled-components";
const Span = styled.span``;
const Button = styled(({ className }) => {
return (
);
})`
${Span} {
color: orange;
}
`;
test("the color of the component is orange", () => {
const renderResult = render();
const button = renderResult.queryByRole("button");
expect(button).toHaveStyleRule("color", "orange", {
modifier: css`
${Span}
`
});
});modifierstyled-componentscss
git cloneyarn && yarn test