Files
evig/vitest.setup.ts
GandMao Nakamoto 9c4db60947 chore: migrate from jest to vitest (#429)
* chore: migrate from jest to vitest

Retires jest in favor of vitest across the whole test suite (541 files,
7780 tests, 100% passing both before and after -- same counts as the
jest baseline, nothing lost or skipped). Same fleet-wide migration
pattern already shipped in botsmann and aoz-housing.

What changed:
- vitest.config.ts / vitest.setup.ts replace jest.config.js /
  jest.setup.js. Single jsdom environment (matching this repo's
  next/jest config) with per-file `@vitest-environment node` overrides
  where jest used `@jest-environment node` (241 files -- vitest supports
  the same docblock convention under a different tag name).
- next-intl's moduleNameMapper aliased both the bare specifier and every
  subpath (next-intl/routing, next-intl/navigation) to __mocks__/next-intl.js;
  vitest's resolve.alias needs the same regex-based subpath match, and the
  mock file itself needed converting off jest.fn()/CJS require to
  vi.fn()/ESM import (nothing else used it, so it never surfaced under jest).
- jest.* -> vi.* across the board: fn/mock/spyOn/clearAllMocks/etc.,
  jest.requireActual -> await vi.importActual (vitest has no sync
  variant), jest.requireMock -> await import() (a dynamic import of an
  already-vi.mock()'d specifier resolves to the mock), jest.setTimeout ->
  vi.setConfig({ testTimeout }), jest.isolateModules -> vi.resetModules()
  + await import() (vitest has no direct equivalent), bare require()
  calls inside test bodies -> await import() (vitest's ESM runtime has no
  require() that understands the `@/` Vite alias).
- Two genuine jest/vitest behavioral differences, not just API renames:
  vitest's vi.fn() invokes `new Foo()` on the mockImplementation itself
  (jest.fn() does not), so any mock standing in for a constructor
  (Audio, pg's Pool, @aws-sdk/client-s3's S3Client/PutObjectCommand/
  DeleteObjectCommand) needed its arrow-function implementation changed
  to a real function. And @testing-library's waitFor polls with real
  timers, which hangs once vi.useFakeTimers() is active in the same
  test -- the two debounce-search tests in useMarketplaceListings that
  combined both now assert directly after an explicit
  vi.advanceTimersByTimeAsync() + microtask flush instead of polling.
- Partial mocks (fs, sharp, and several @/db/schema* mocks) needed the
  same treatment already documented from the aoz-housing migration:
  vitest validates a mocked module's exports strictly, so a default
  import needs a `default` key in the mock factory's return value (jest
  didn't check this), and every export the mocked module's *transitive*
  importers reach for has to actually be present.
- vitest's own Mock/MockedFunction/MockedClass/MockInstance/Mocked types
  replace the jest.Mock family (SpyInstance is renamed MockInstance).
- One real source fix, not a test-only shim: blog-translate.ts zeroed
  its retry backoff under test by checking `process.env.JEST_WORKER_ID`;
  vitest sets `VITEST` instead, so two of its tests were hitting the
  real 2s/4s production backoff and timing out. Now checks both.
- package.json: test/test:watch/test:coverage/test:i18n scripts point
  at vitest; jest, @types/jest, jest-environment-jsdom dropped from
  devDependencies (@testing-library/jest-dom stays -- it's a matcher
  library, not jest-specific, and vitest uses it too).
- vitest-globals.d.ts (`/// <reference types="vitest/globals" />`)
  replaces the ambient describe/it/expect types @types/jest used to
  provide, without touching tsconfig's `types` array (which has no
  explicit list today, so every other @types/* package stays
  auto-included exactly as before).
- A related, pre-existing typecheck gap this migration exposed rather
  than introduced: `require('@/lib/schemas')` returned an untyped `any`
  under jest/CJS, so a cast like `as { validateBody: Mock }` type-checked
  even though the shapes don't really overlap. `await import(...)` is
  properly typed against the real module, so those same casts now need
  `as unknown as {...}` (or `as any` for the common case of a plain
  destructured mock-only import) -- a standard TS idiom, not a behavior
  change, verified by a full green `npm run typecheck` and `npm run lint`
  alongside the test run.

No source-level logic changes outside the one RETRY_BASE_MS env-var
guard above. `npm run typecheck`, `npm run lint`, and `npm run test`
(vitest) all pass clean.

* fix(deps): regenerate lockfile without --legacy-peer-deps

The previous commit's package-lock.json was produced with
--legacy-peer-deps (needed at the time to work around an
@vitejs/plugin-react / @rolldown/plugin-babel optional-peer conflict).
That flag changes npm's resolution algorithm significantly and produced
a lockfile missing large dependency subtrees entirely -- webpack and
everything under it -- causing real CI's `npm ci` (a strict,
lockfile-must-match-package.json install) to fail with EUSAGE before a
single test could run.

A plain `npm install` (no flag) resolves the same peer conflict fine
with warnings only, and `npm ci` against the regenerated lockfile now
succeeds cleanly. Verified: npm ci, npm run typecheck, npm run lint,
and the full vitest suite (541/541 files, 7780/7780 tests) all pass
against this lockfile.

* style: run prettier over the vitest migration

The scripted jest->vitest rewrites in the previous two commits weren't
run through prettier, and CI's Code Quality Checks job caught it:
"Code style issues found in 152 files." Converged in a single
`npm run format` pass; verified no eslint-disable-next-line or
@ts-expect-error directive detached from its target line, and
typecheck/lint/test all still pass clean.

* fix(test): drop a hoisted vi.mock that raced its own per-test override

audit.test.ts had both a hoisted, file-level `vi.mock('@/db', ...)` and
a per-test `vi.doMock('@/db', ...)` inside beforeEach that reassigns
valuesSpy fresh after vi.resetModules(). This is a documented vitest
anti-pattern: after resetModules(), which of the two mock
registrations actually backs the next import of '@/db' depends on
internal cache-invalidation timing, not test source order. It surfaced
as an intermittent "undefined is not a spy" on CI (real, dedicated
runner -- not local machine contention) roughly 1 run in 4: the
hoisted mock's plain `insert: vi.fn()` (no values() return) occasionally
won the race, so valuesSpy was never assigned by the doMock factory
that test iteration.

beforeEach runs before every test including the first, so the per-test
doMock alone is sufficient -- no top-level fallback needed. Verified
5 consecutive clean runs of this file after the fix.

---------

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
2026-09-02 10:43:17 +02:00

102 lines
2.7 KiB
TypeScript

import { TextEncoder, TextDecoder } from 'util';
import '@testing-library/jest-dom';
import { vi } from 'vitest';
// Polyfill TextEncoder/TextDecoder for jsdom environment (needed by pg/Drizzle)
global.TextEncoder = TextEncoder as unknown as typeof global.TextEncoder;
global.TextDecoder = TextDecoder as unknown as typeof global.TextDecoder;
// Mock Next.js router
vi.mock('next/router', () => ({
useRouter() {
return {
route: '/',
pathname: '/',
query: '',
asPath: '/',
push: vi.fn(),
pop: vi.fn(),
reload: vi.fn(),
back: vi.fn(),
prefetch: vi.fn().mockResolvedValue(undefined),
beforePopState: vi.fn(),
events: {
on: vi.fn(),
off: vi.fn(),
emit: vi.fn(),
},
};
},
}));
// Mock next-auth
vi.mock('next-auth/react', () => ({
useSession: vi.fn(() => ({
data: null,
status: 'unauthenticated',
})),
signIn: vi.fn(),
signOut: vi.fn(),
getSession: vi.fn(),
}));
// Mock next-auth (server-side)
vi.mock('next-auth', () => ({
auth: vi.fn(() => Promise.resolve(null)),
}));
// Mock fetch
global.fetch = vi.fn();
// Browser-only mocks (skip in node environment for API route tests)
if (typeof window !== 'undefined') {
// jsdom has no PointerEvent -- without it, testing-library's
// fireEvent.pointerDown/Move/... falls back to a bare Event that silently
// drops pointerType, button, clientX/Y and modifier keys. Extending
// MouseEvent keeps all of those and adds the pointer fields.
if (typeof window.PointerEvent === 'undefined') {
class PointerEventPolyfill extends MouseEvent {
pointerType: string;
pointerId: number;
isPrimary: boolean;
constructor(type: string, init: PointerEventInit = {}) {
super(type, init);
this.pointerType = init.pointerType ?? '';
this.pointerId = init.pointerId ?? 1;
this.isPrimary = init.isPrimary ?? true;
}
}
// @ts-expect-error -- polyfill assignment, not a real PointerEvent subclass
window.PointerEvent = PointerEventPolyfill;
}
// Mock window.matchMedia
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation((query) => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(), // deprecated
removeListener: vi.fn(), // deprecated
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
// Mock IntersectionObserver
global.IntersectionObserver = class IntersectionObserver {
constructor() {}
observe() {
return null;
}
disconnect() {
return null;
}
unobserve() {
return null;
}
} as unknown as typeof IntersectionObserver;
}