Skip to content

Instantly share code, notes, and snippets.

@juhosa
Last active December 9, 2022 07:28
Show Gist options
  • Save juhosa/bf07be3aa03ba4c5bc8f5836aa6f4bec to your computer and use it in GitHub Desktop.
Save juhosa/bf07be3aa03ba4c5bc8f5836aa6f4bec to your computer and use it in GitHub Desktop.
Steps to setup tests in vite (react) project
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import App from "../App";
import userEvent from "@testing-library/user-event";
describe("testing App component", async () => {
it("header is shown", () => {
render(<App />);
expect(screen.getByText(/empty template/i)).toBeInTheDocument();
});
it("button click works", async () => {
const user = userEvent.setup();
render(<App />);
const btn = screen.getByRole("button", { name: "save" });
await userEvent.click(btn);
const text = screen.getByText("clicked");
expect(text).toBeInTheDocument();
});
});
  1. Install libraries
npm install vitest jsdom @testing-library/react @testing-library/jest-dom @testing-library/user-event
  1. This stuff into the vite config file
export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: "jsdom",
    setupFiles: "./src/test/setup.js",
  },
})
  1. Create src/test/setup.js
import "@testing-library/jest-dom"
  1. Add 'test'-script to package.json
"test": "vitest"
  1. Write tests into './src/test' -directory

Filenames are like ComponentName.test.jsx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment