
import { styled } from "styled-components";
import { ColorKey, HeadingSize } from "../../style/theme";
interface Props {
children: React.ReactNode;
size: HeadingSize;
color?: ColorKey;
}
function Title({ children, size, color }: Props) {
return (
<TitleStyle size={size} color={color}>
{children}
</TitleStyle>
);
}
const TitleStyle = styled.h1<Omit<Props, "children">>`
font-size: ${({ theme, size }) => theme.heading[size].fontSize};
color: ${({ theme, color }) =>
color ? theme.color[color] : theme.color.primary};
`;
export default Title;
요게 Title.tsx이고 이걸 Title.spec.tsx으로 테스트를 해보려고 하는데 어떻게 하냐면,
"Title 컴포넌트가 제대로 동작하는지 자동으로 확인하는 코드"
describe("Title 컴포넌트", () => {
// 여기에 테스트들이 들어감
});
describe: "이 컴포넌트에 대한 테스트들이야" 라고 묶어주는 거임it 테스트가 들어감it("렌더를 확인", () => {
// 1. 렌더
render(
<BookStoreThemePrivider>
<Title size="large">제목</Title>
</BookStoreThemePrivider>
);
// 2. 확인
expect(screen.getByText("제목")).toBeInTheDocument();
});
뭐 하는 거냐?
render: Title 컴포넌트를 화면에 그림expect: "제목"이라는 텍스트가 화면에 있는지 확인it("size props 적용", () => {
const { container } = render(
<BookStoreThemePrivider>
<Title size="medium">제목</Title>
</BookStoreThemePrivider>
);
expect(container.firstChild).toHaveStyle("font-size: 1.5rem");
});
뭐 하는 거냐?
size="medium" 넣었을 때font-size: 1.5rem 스타일이 적용되는지 확인it("color props 적용", () => {
const { container } = render(
<BookStoreThemePrivider>
<Title size="medium" color="primary">
제목
</Title>
</BookStoreThemePrivider>
);
expect(container.firstChild).toHaveStyle("color: brown");
});
뭐 하는 거냐?
color="primary" 넣었을 때color: brown (테마의 primary 색상) 적용되는지 확인<BookStoreThemePrivider>
<Title size="large">제목</Title>
</BookStoreThemePrivider>
Title 컴포넌트가 theme을 사용하니까!
컴포넌트를 테스트용 화면에 그림
render(<Title>제목</Title>);
화면에서 특정 텍스트 찾기
screen.getByText("제목"); // "제목"이라는 글자 찾기
"이게 이래야 해!" 라고 확인
expect(A).toBeInTheDocument(); // A가 화면에 있어야 함
expect(A).toHaveStyle("color: red"); // A가 이 스타일 가져야 함
1. 코드 수정해도 안심하고 수정 가능
// Title 컴포넌트 수정 후
npm run test // 테스트 실행
// 통과하면 → 문제없음!
// 실패하면 → 뭔가 망가뜨림!
2. 협업할 때 유용
3. 버그 미리 발견
npm run test
결과:
✓ 렌더를 확인
✓ size props 적용
✓ color props 적용
Tests: 3 passed, 3 total
describe: 테스트 묶음it: 개별 테스트render: 컴포넌트 그리기expect: 제대로 동작하는지 확인"자동으로 내 컴포넌트 검사해주는 코드"임!