Skip to content

Latest commit

 

History

History
113 lines (79 loc) · 1.97 KB

File metadata and controls

113 lines (79 loc) · 1.97 KB

Testing React-Application

Goods and Bads

Test Pyramid

Classifications

Test Classifications

Setup

Jest

TBD

Playwright

TBD

Vitest

npm install -D vitest jsdom @vitejs/plugin-react @testing-library/react @testing-library/jest-dom

package.json

"scripts": {
  "test": "vitest",
}

vite.config.ts

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'jsdom',
    setupFiles: 'src/tests/setup.js',
  },
});

tests/setup.js

import { expect, afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
import matchers from '@testing-library/jest-dom/matchers';

// extends Vitest's expect method with methods from react-testing-library
expect.extend(matchers);

// runs a cleanup after each test case (e.g. clearing jsdom)
afterEach(() => {
  cleanup();
});

Running tests

npm test

Implementing tests

  • Follow Arrange, Act, Assert (AAA)
  • Consider the Test-Pyramid
import { describe, expect, it } from "vitest";
import { render, screen } from "@testing-library/react";
import Header from "../components/Header";

describe("App", () => {
  it("renders headline", () => {
    render(<Header />);

    screen.debug();
  });
});

describe("Example", () => {
  it("1 should be 1", () => {
    expect(1).toEqual(1);
  });
});

Testing React

Examples