Styled-Component 테스트하기

방구석 코딩쟁이·2024년 1월 29일
0

Next.JS + Styled Component를 테스트할 경우가 발생했었습니다.

제가 테스트하고 싶은 코드는 아래와 같습니다.

"use client";
import styled from "styled-components";

const ButtonContainer = styled.div`
  background-color: #304ffe;
  &:hover {
    background-color: #1e40ff;
  }
`;

export default ButtonContainer;

버튼을 hover할 때와 아닐 때가 달라지는 경우에 대해 테스트를 하고자 했습니다.

이 때, 기존 jesttoHaveStyle() 메서드만 가지고는 테스트가 잘 안되었습니다.

이를 위해서, jest-styled-components 패키지를 설치하였습니다.

그리고 테스트하고 싶은 파일에jest-styled-components 패키지를 import한 후에, toHaveStyleRule() 메서드를 통해 테스트를 진행하니 에러가 해결되었습니다.

import { render, screen } from "@testing-library/react";
import Button from "../styled/Button";
import "jest-styled-components";

describe("<Button/>", () => {
  it("renders component correctly", () => {
    render(<Button label="추가" />);

    const button = screen.getByText("추가");
    expect(button).toBeInTheDocument();

    const parent = screen.getByTestId("container");
    expect(parent).toContainElement(button);

    expect(parent).toHaveStyleRule("background-color", "#304ffe");
    expect(parent).toHaveStyleRule("background-color", "#1e40ff", {
      modifier: ":hover",
    });
  });
});
profile
풀스택으로 나아가기

0개의 댓글