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
color
expect
expect.any
color
expect(renderResult.queryByRole("button")).toHaveStyleRule(
"color",
expect.any(String)
);
styled-components
button { }
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: blue
color: 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}
`
});
});
modifier
styled-components
css
git clone
yarn && yarn test