技术栈:
vite
react
vitest
testing-library/react
testing-library/jest-dom
// test/comment.test.jsx
import { it, expect } from "vitest";
import { screen, render } from "@testing-library/react";
import { userEvent } from "@testing-library/user-event";
import CommentTitle from "../components/Comment/CommentTitle";
it("There should be a sorting icon, which upon hovering, displays a list containing two items: Hottest First and Newest First. Beside the icon, there's text reading 'Sort'.", async () => {
const user = userEvent.setup();
render(<CommentTitle commentListLength={0} />);
expect(screen.queryByText("sort")).not.toBeNull();
const sortByIcon = screen.queryByTestId("sort-by-icon");
expect(sortByIcon).not.toBeNull();
expect(screen.queryByText("Hottest First")).not.toBeVisible();
expect(screen.queryByText("Newest First")).not.toBeVisible();
await user.hover(sortByIcon);
expect(screen.queryByText("Hottest First")).toBeVisible();
expect(screen.queryByText("Newest First")).toBeVisible();
});
手动测试不应该失败,但自动化测试在第二次期望时失败。
使用
screen.logTestingPlaygroundURL()
,我发现一些 Tailwind CSS 样式不适用。当我设置内联样式 display: none
时,初始状态测试通过,但之后仍然失败(因为我无法将伪类应用于内联样式)。
// src/components/CommentTitile.jsx
import Proptypes from "prop-types";
import { MdSort } from "react-icons/md";
function CommentTitle({ commentListLength }) {
return (
<div
data-testid="comment-title"
className="flex flex-row items-center gap-6 mb-20 "
>
<span data-testid="number-of-comments">
comments{commentListLength || ""}
</span>
<div className="flex flex-row gap-2 items-center">
<div className="flex flex-row items-center relative cursor-pointer">
<div className="self-start text-lg peer" data-testid="sort-by-icon">
<MdSort />
</div>
<ul className="peer-hover:block hidden absolute rounded whitespace-pre top-6 left-1/2 -translate-x-1/2 p-2">
<li>Hottest First</li>
<li>Newest First</li>
</ul>
</div>
<div data-testid="sort-text">sort</div>
</div>
</div>
);
}
...
添加配置仍然无法解决问题。
// testSetup.js
import "@testing-library/jest-dom/vitest";
import "./src/index.css"; // add that line
// vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
test: {
setupFiles: "./testSetup.js",
globals: true,
environment: "jsdom",
css: true, // add that line
},
});
补充:
嘿,看完 this other post 并且因为您没有显示
src/index.css
的内容,我建议尝试添加这些行以查看它是否添加了测试所需的 css。
@tailwind base;
@tailwind components;
@tailwind utilities;
我只是想知道您是否遇到另一个问题完全是因为您说使用调试日志时某些样式不适用。