# Setting Up Jest or Vitest — Jest, Vitest & Testing Library

Source: https://www.skillbyai.com/en/javascript-testing/f-setup

> Config files, test environments and setup files.

## Environment: node, jsdom or happy-dom

Both runners default to a **node** environment, which has no `document` or `window`. Component tests need a simulated DOM: **jsdom** (the long-standing, more complete implementation) or **happy-dom** (a lighter, often faster alternative; Vitest supports it directly). In Jest you set `testEnvironment: 'jsdom'` and, in recent Jest versions, install `jest-environment-jsdom` separately. In Vitest you set `test.environment` and install the matching package. A **setup file** runs before each test file; it is the place to add `@testing-library/jest-dom` matchers, start an MSW server or reset mocks. You can also set the environment per file with a docblock comment such as `@vitest-environment jsdom` or `@jest-environment jsdom`. Exact package names and defaults change between major versions, so check the docs for yours.

## Minimal configs for each runner

Install commands are shown, not run.

```typescript
// --- Vitest: vitest.config.ts (or a `test` block in vite.config.ts) ---
// npm i -D vitest jsdom @testing-library/react @testing-library/jest-dom @testing-library/user-event
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',           // or 'happy-dom'
    globals: true,                  // optional: describe/it/expect without imports
    setupFiles: ['./src/test/setup.ts'],
  },
});

// src/test/setup.ts
import '@testing-library/jest-dom/vitest';   // adds toBeInTheDocument() etc.

// --- Jest: jest.config.ts ---
// npm i -D jest jest-environment-jsdom ts-jest @types/jest @testing-library/jest-dom ...
import type { Config } from 'jest';

const config: Config = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['<rootDir>/src/test/setup.ts'],
  moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1' },   // mirror your path aliases
};
export default config;
```

## Add npm scripts early

Add `"test": "vitest"` (watch mode locally) and `"test:ci": "vitest run"`, or `"test": "jest"` and `"test:watch": "jest --watch"`, so every developer and the CI job run tests the same way.

**Quiz:** Why do component tests need jsdom or happy-dom?

- [ ] They replace the assertion library
- [ ] They make tests run in Chrome
- [ ] They compile TypeScript
- [x] The default node environment has no document or window for components to render into

*Answer:* The default node environment has no document or window for components to render into. A simulated DOM is what rendering and querying need.
