跳到主要内容

测试

Jest

安装

pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom

配置文件

  • jest.config.js;
import type { Config } from "jest";
import nextJest from "next/jest.js";

const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: "./",
});

// Add any custom config to be passed to Jest
const config: Config = {
coverageProvider: "v8",
testEnvironment: "jsdom",
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
moduleNameMapper: {
// ...
"^@/components/(.*)$": "<rootDir>/components/$1",
},
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config);

测试命令

{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest",
"test:watch": "jest --watch"
}
}

普通测试

import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import Page from "../app/page";

describe("Page", () => {
it("renders a heading", () => {
render(<Page />);

const heading = screen.getByRole("heading", { level: 1 });

expect(heading).toBeInTheDocument();
});
});

快照测试

import { render } from "@testing-library/react";
import Page from "../app/page";

it("renders homepage unchanged", () => {
const { container } = render(<Page />);
expect(container).toMatchSnapshot();
});