npm install -D vitest @testing-library/react @testing-library/jest-dom @vitejs/plugin-react jsdom
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
import { resolve } from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": resolve(__dirname, "./src"), // src폴더 안에 __test__ 폴더 생성
},
},
test: {
// window 나 document 같은 전역 변수를 사용하도록 허용한다.
globals: true,
environment: "jsdom",
setupFiles: "./src/__tests__/index.test.tsx",
},
});
{
"name": "vitesttest",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"test": "vitest"
},
"dependencies": {
"@next/font": "13.4.7",
"@types/node": "20.3.1",
"@types/react": "18.2.13",
"@types/react-dom": "18.2.6",
"eslint": "8.43.0",
"eslint-config-next": "13.4.7",
"next": "13.4.7",
"react": "18.2.0",
"react-dom": "18.2.0",
"typescript": "5.1.3"
},
"devDependencies": {
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.0.0",
"@vitejs/plugin-react": "^4.0.1",
"jsdom": "^22.1.0",
"vitest": "^0.32.2"
}
}
export default function Home() {
return (
<>
<div>
<button style={{ backgroundColor: "rgb(255, 0, 0)" }}>
Change to blue
</button>
</div>
</>
);
}
import { expect, test } from "vitest";
import { render, screen } from "@testing-library/react";
import matchers from "@testing-library/jest-dom/matchers";
import Home from "@/app/page";
expect.extend(matchers);
test("Home", () => {
render(<Home />);
// find a role
const colorButton = screen.getByRole("button", { name: "Change to blue" });
// button's color is red
expect(colorButton).toHaveStyle({ backgroundColor: "rgb(255, 0, 0)" });
});
정상적으로 잘 작동 된다!