使用Jest在React应用中测试Tailwind剪枝

oprakyz7  于 2023-08-01  发布在  Jest
关注(0)|答案(1)|浏览(97)

有没有一种方法可以用Jest测试Tailwind的修剪,而不必编写自定义postcss配置,只实现CRA 5创建的默认webpack配置(也实现了here)。
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);
  });
});

zf9nrax1

zf9nrax11#

// 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");
});

字符串

相关问题