ferroxlabs/wayland/javascript-testing-patterns

Claude Code and agent skill by ferroxlabs/wayland

Trust tier 3
  • community
  • ext:[{"type":"config","description":"Configuration overrides"},{"type":"plugin","description":"Custom plugin integration"}]
Source check pending

Checking that the SKILL.md file is still in the repository.

Guides expert-level JavaScript and TypeScript testing: Vitest vs Jest decision tree, ESM mocking strategies, snapshot testing, coverage configuration, and test runner selection for modern projects. Use when the user asks about JavaScript testing, Vitest, Jest, mocking ESM, snapshot testing, coverage, test runner selection, TypeScript testing. Do NOT use when the user asks about Node.js project setup (use `nodejs-project-setup`), general testing concepts (use `unit-testing-patterns`), E2E testing (use `e2e-testing-patterns`).

Install

npx vskill@latest install ferroxlabs/wayland/javascript-testing-patterns

Semi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard

SKILL.md

The same SKILL.md was published earlier as ferroxlabs/wayland/javascript-testing-patterns.

JavaScript Testing Patterns

When to Use

Use this skill when the user asks about:

  • Choosing between Vitest and Jest for a new or existing JavaScript/TypeScript project
  • Mocking ES modules (ESM) -- import statements, dynamic import(), or packages that only ship ESM
  • Configuring test coverage thresholds, Istanbul/V8 providers, and coverage exclusion patterns
  • Setting up snapshot testing, inline snapshots, or snapshot update workflows
  • Testing TypeScript code including type-level assertions, declaration testing, or ts-jest vs native TypeScript support
  • Writing tests for async/await code, Promises, timers, or event emitters
  • Structuring test files, fixture patterns, and factory functions for complex domain objects
  • Migrating a Jest codebase to Vitest or upgrading a legacy Babel-Jest pipeline
  • Configuring test parallelism, worker threads, and test isolation modes
  • Writing parameterized/data-driven tests for multiple input/output scenarios

Do NOT use this skill when:

  • The user needs to initialize a Node.js project from scratch -- use nodejs-project-setup instead
  • The user is asking about general testing vocabulary (unit vs. integration vs. contract) without a JavaScript-specific angle -- use unit-testing-patterns
  • The user needs Playwright, Cypress, Puppeteer, or any browser-driven E2E testing -- use e2e-testing-patterns
  • The user is asking about React component testing with React Testing Library as the primary concern -- this skill covers the runner/mocking layer; a component-testing skill covers the rendering layer
  • The user is asking about API contract testing with Pact or schema validation tools
  • The user is asking about performance benchmarking frameworks (Vitest bench is adjacent but out of scope here)

Process

1. Identify the Project Context and Constraints

Before recommending any tooling, gather the facts that determine every downstream decision.

  • Module system in use: Is the project CommonJS ("type": "module" absent or require() throughout), pure ESM ("type": "module" in package.json), or a hybrid with both? ESM-only projects rule out certain Jest configurations that rely on synchronous require() transforms.
  • Bundler/transpiler in use: Vite projects are almost always better served by Vitest. Webpack or esbuild projects work fine with either. Babel-only projects that rely on @babel/preset-env need extra care when switching runners.
  • TypeScript version and config strictness: TypeScript ≥ 5.0 with "moduleResolution": "bundler" or "node16" changes how test runners locate .d.ts files and how path aliases are resolved.
  • Existing test investment: Count existing test files. Fewer than 50 tests -- migrate fully. 50-500 tests -- run both runners in parallel during transition. 500+ tests -- migrate by package/folder boundary.
  • CI time budget: Ask about acceptable test suite wall-clock time. Vitest's thread-based parallelism with a shared worker pool typically runs 1.5x--3x faster than Jest on suites with many small tests. Jest's --runInBand is essential for database integration tests to avoid connection pool exhaustion.
  • Browser/JSDOM requirement: Tests needing browser globals (window, document, localStorage) require JSDOM or Happy-DOM environments. Configure this at the file level with @vitest-environment jsdom docblock or in vitest.config.ts per glob pattern.
2. Choose the Test Runner -- Apply the Decision Tree

This is the highest-leverage decision. It is difficult to reverse without migrating test files.

  • Start with Vitest if:
  • The project uses Vite as its build tool (Vitest reuses the same Vite config, plugin pipeline, and alias resolution -- zero duplication)
  • The project is pure ESM or TypeScript-first (Vitest handles both natively without Babel)
  • The team wants native TypeScript support without ts-jest or a Babel transform
  • Hot Module Replacement (HMR) in watch mode matters (Vitest re-runs only affected tests, not the full suite)
  • The project needs inline type-checking during tests using vitest --typecheck
  • Keep or adopt Jest if:
  • The project uses Create React App, Next.js (non-Turbopack), or NestJS -- all ship with first-class Jest support
  • The team has deep Jest institutional knowledge and a large snapshot corpus
  • The project requires jest-circus, jest-jasmine2, or custom runners for complex async scheduling
  • Third-party testing utilities (e.g., @testing-library/jest-dom, MSW v1 handlers) are tightly coupled to Jest's global injection model
  • The project targets Node.js ≤ 16 where Vitest's ESM requirements are harder to satisfy
  • During migration from Jest to Vitest:
  • Install vitest and add "test": "vitest" as a parallel script alongside "test:jest": "jest"
  • Vitest's API is Jest-compatible for describe, it, expect, beforeEach, afterEach, vi (equivalent to jest)
  • Replace jest.fn() with vi.fn(), jest.mock() with vi.mock(), jest.spyOn() with vi.spyOn()
  • jest.useFakeTimers() becomes vi.useFakeTimers() -- behavior is nearly identical
  • Globals (describe, it, expect) are opt-in in Vitest via globals: true in config -- set this first to avoid modifying every test file during migration
3. Configure the Runner -- Specific Settings That Matter

A correct configuration prevents hours of debugging mysterious test failures.

Vitest configuration (`vitest.config.ts`):

typescript
import { defineConfig } from 'vitest/config'
import tsconfigPaths from 'vite-plugin-tsconfig-paths'
export default defineConfig({
plugins: [tsconfigPaths()],
test: {
globals: true, // expose describe/it/expect globally
environment: 'node', // or 'jsdom', 'happy-dom', 'edge-runtime'
include: ['src/**/*.{test,spec}.{ts,tsx}'],
exclude: ['node_modules', 'dist', 'e2e/**'],
setupFiles: ['./src/test/setup.ts'],
coverage: {
provider: 'v8', // faster; use 'istanbul' for branch accuracy
reporter: ['text', 'lcov', 'html'],
include: ['src/**/*.{ts,tsx}'],
exclude: ['src/**/*.d.ts', 'src/**/*.test.ts', 'src/test/**'],
thresholds: {
lines: 80,
branches: 75,
functions: 80,
statements: 80,
},
},
pool: 'threads', // 'forks' for Node.js child processes; use for native modules
poolOptions: {
threads: { singleThread: false },
},
},
})

Jest configuration (`jest.config.ts`):

typescript
import type { Config } from 'jest'
const config: Config = {
preset: 'ts-jest/presets/default-esm', // for ESM TypeScript
testEnvironment: 'node',
extensionsToTreatAsEsm: ['.ts'],
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1', // rewrite .js imports to resolve .ts files
'^@/(.*)$': '<rootDir>/src/$1',
},
transform: {
'^.+\\.tsx?$': ['ts-jest', { useESM: true }],
},
collectCoverageFrom: [
'src/**/*.{ts,tsx}',
'!src/**/*.d.ts',
'!src/**/*.test.{ts,tsx}',
'!src/test/**',
],
coverageThreshold: {
global: { lines: 80, branches: 75, functions: 80, statements: 80 },
},
testMatch: ['<rootDir>/src/**/*.test.{ts,tsx}'],
}
export default config

Key settings with rationale:

  • pool: 'threads' in Vitest uses worker_threads -- fast but cannot load native .node addons. Use pool: 'forks' for projects with native modules (e.g., sharp, bcrypt, sqlite3).
  • environment: 'happy-dom' is 10-15x faster than jsdom for pure DOM manipulation tests. Use jsdom when tests rely on specific CSS layout behavior or MutationObserver edge cases.
  • setupFiles runs before each test file in isolation. globalSetup runs once before all tests and cannot access vi/jest globals -- use for starting database servers or mock HTTP servers.
4. Design the Mocking Strategy -- ESM Is the Hard Part

ESM mocking is the most common source of confusion and broken tests. Apply these patterns precisely.

Static ESM mock with `vi.mock()` / `jest.mock()` (hoisted):

typescript
// Module mocking is HOISTED to the top of the file by the test runner,
// even if written later in the source. This is not normal JS execution order.
vi.mock('../services/emailService', () => ({
sendEmail: vi.fn().mockResolvedValue({ messageId: 'test-123' }),
validateAddress: vi.fn().mockReturnValue(true),
}))
// For modules with a default export:
vi.mock('../utils/logger', () => ({
default: {
info: vi.fn(),
error: vi.fn(),
warn: vi.fn(),
},
}))

The ESM interop problem and solution:

  • Packages distributed as pure ESM (e.g., node-fetch v3, chalk v5, nanoid v4, execa v7) cannot be mocked with synchronous jest.mock() in standard Jest + Node.js because Jest's module registry uses CommonJS require() internally.
  • Solution 1 (preferred for Jest): Use jest-mock-extended or add "transformIgnorePatterns": [] and transform the ESM package through Babel. In jest.config.ts: transformIgnorePatterns: ['node_modules/(?!(node-fetch|chalk|nanoid)/)'].
  • Solution 2: Wrap the ESM dependency in a thin adapter module you own. Mock the adapter, not the package. This also decouples your code from the vendor API.
  • Solution 3 (Vitest): Vitest handles ESM natively -- vi.mock('node-fetch') works without transforms because Vitest operates on the same ESM graph as Vite.

Spying without replacing (non-destructive mocking):

typescript
import * as fs from 'node:fs/promises'
const readFileSpy = vi.spyOn(fs, 'readFile').mockResolvedValue('file content' as any)
afterEach(() => {
vi.restoreAllMocks() // resets ALL spies created with spyOn
})

Manual mocks (`__mocks__` directory):

  • Place a file at src/__mocks__/nodemailer.ts to auto-mock the nodemailer package for all tests in the project.
  • For relative imports, the __mocks__ directory must be adjacent to the module being mocked.
  • Call vi.mock('nodemailer') or jest.mock('nodemailer') in the test file to activate the manual mock -- it does not activate automatically for non-node_modules packages.

Timer mocking:

typescript
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2024-01-15T10:00:00Z')) // deterministic "now"
})
afterEach(() => {
vi.useRealTimers()
})
it('retries after 5 seconds', async () => {
const promise = retryWithDelay(operation, { delayMs: 5000, maxAttempts: 3 })
await vi.advanceTimersByTimeAsync(5000) // advances fake clock AND flushes promises
expect(operation).toHaveBeenCalledTimes(2)
})
5. Design Fixtures and Test Data Factories

Poor data setup is the second most common source of flaky or hard-to-read tests.

Object Mother / Factory function pattern:

typescript
// src/test/factories/user.factory.ts
import { User } from '../domain/user'
let idCounter = 0
export function createUser(overrides: Partial<User> = {}): User {
return {
id: `user-${++idCounter}`,
email: `user${idCounter}@example.com`,
name: 'Test User',
role: 'member',
createdAt: new Date('2024-01-01T00:00:00Z'),
isActive: true,
...overrides,
}
}
// Usage in tests -- explicit only what matters:
const adminUser = createUser({ role: 'admin' })
const inactiveUser = createUser({ isActive: false, email: 'inactive@example.com' })

Reset state between tests:

  • Reset the idCounter in beforeEach or use a closure that resets on module load per test
  • In Vitest, use vi.isolateModules() to get a fresh module instance including its internal state
  • Never share mutable fixtures between describe blocks across different test files

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
5

Not refreshed yet.

Extension points

  • configConfiguration overrides
  • pluginCustom plugin integration

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/ferroxlabs/wayland/javascript-testing-patterns/badge)](https://verified-skill.com/skills/ferroxlabs/wayland/javascript-testing-patterns)

Something wrong with this skill or its page? Tell us.