웹사이트 검색

reactjs - Jest로 React 앱에서 Tailwind 가지치기 테스트하기


CRA 5에서 생성한 기본 웹팩 구성만 구현하고(여기에서도 구현됨), 커스텀 PostCSS 구성을 작성하지 않고 Jest로 Tailwind의 가지치기를 테스트할 수 있는 방법이 있나요?

Tailwind는 .test.tsx 파일 안의 모든 클래스를 무시하는 것 같고 출력에 포함하지 않습니다.

다음은 관련 파일입니다:

tailwind.config.js

module.exports = {
  content: ["./src/**/*.{html,js,jsx,ts,tsx,test.jsx,test.tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};

index.tsx

import React from "react";
import ReactDOM from "react-dom/client";
import "./styles/index.scss";
import App from "./Views/App/App";

const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

index.scss

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

body {
  ...
}

App.test.tsx:

import { render, screen } from "@testing-library/react";

describe("Tailwind Pruning", () => {
  test("Should include style", () => {
    const expected = "rgb(220, 38, 38)";

    render(<span className="text-red-600" data-testid="tailwind-test"></span>);
    const dom = screen.getByTestId("tailwind-test");
    const actual = getComputedStyle(dom).color;

    expect(actual).toBe(expected);
  });

  // tailwind should fail to include the style for this test
  test("Should not include style", () => {
    const expected = "";

    render(<span className={`${"text"}-${"red"}-${600}`} data-testid="tailwind-test"></span>);
    const dom = screen.getByTestId("tailwind-test");
    const actual = getComputedStyle(dom).color;

    expect(actual).toBe(expected);
  });
});

답변 #1

// jest.config.js

module.exports = {
  moduleNameMapper: {
    "\\.(css|less|scss|sass)$": "identity-obj-proxy",
  },
};

// *.test.ts or *.test.js
import React from "react";
import { render } from "@testing-library/react";
import "@testing-library/jest-dom";
import "./styles.css";

test("renders a div with the correct class", () => {
  const { getByTestId } = render(
    <div data-testid="test" className="bg-blue-500"></div>
  );
  const div = getByTestId("test");

  expect(div).toHaveClass("bg-blue-500");
});

답변 #2

저도 2주 전에 이 문제를 겪었고, 이렇게 해서 해결할 수 있었습니다:

  • jest.config.js
module.exports = {
    moduleNameMapper: {
        // all mock names
        '\\.(css|less)$': '<rootDir>/node_modules/tailwindcss', // try to do this, it works without error
    },
}

그리고 작동하는지 확인하고 싶다면, 코드 테스트 케이스 안 어디에서든 debug()를 시도해 보세요. 그러면 코드 안에서 사용한 클래스 이름을 얻을 수 있습니다(이것이 바로 테스트하는 것입니다). 또한 클래스 이름은 스타일링을 위해 변환될 수 있습니다. 제 경우에는 hsl()을 사용했는데, 콘솔 디버깅에서는 rgb()로 표시됩니다.

도움이 되길 바랍니다!