
Javascript Testing
- 19 installs
- 3 repo stars
- Updated January 13, 2026
- shino369/claude-code-personal-workspace
Helps with testing & qa tasks.
About
javascript-testing is a Claude Code skill for testing & qa. It helps solo builders move faster with AI-assisted development.
- javascript-testing
- Testing & QA
- AI-coding skill
Javascript Testing by the numbers
- 19 all-time installs (skills.sh)
- Ranked #1,445 of 2,153 Testing & QA skills by installs in the Skillselion catalog
- Data as of Jul 27, 2026 (Skillselion catalog sync)
npx skills add https://github.com/shino369/claude-code-personal-workspace --skill javascript-testingAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 19 |
|---|---|
| repo stars | ★ 3 |
| Last updated | January 13, 2026 |
| Repository | shino369/claude-code-personal-workspace ↗ |
What it does
Helps with testing & qa tasks.
Files
JavaScript Testing Best Practices
Overview
Comprehensive guidance for writing high-quality JavaScript/Node.js tests using Vitest with 100% code coverage.
Testing Framework: Vitest
Why Vitest:
- Native ESM support (no experimental flags)
- Seamless JSDOM integration
- Faster than Jest
- Jest-compatible API
- Built-in coverage with v8
Test structure:
your-script-dir/
├── script.js
└── __tests__/
└── script.test.jsVitest Globals
Globals available automatically - no imports needed:
describe('myFunction', () => {
test('should work', () => {
expect(true).toBe(true);
});
beforeEach(() => {
/* Setup */
});
afterEach(() => {
/* Cleanup */
});
});Available globals: describe, test, it, expect, beforeEach, afterEach, beforeAll, afterAll, vi
Only import vi when mocking:
import { vi } from 'vitest';
vi.mock('module-name');Coverage Requirements
100% Required For
- All scripts in
.claude/hooks/ - All scripts in
.claude/skills/ - All utilities in
utils/ - Business logic scripts
- Data processing scripts
- API interaction scripts
Check coverage:
pnpm test:coverage
# Must show 100% for: Statements, Branches, Functions, LinesTests Optional For
- One-off automation scripts
- Shell command wrappers
- Throwaway/experimental scripts in
output/tasks/
Core Principles
1. Rarely Use Coverage Ignore
General Rule: Refactor code to be testable instead of ignoring coverage.
❌ Don't ignore testable business logic:
/* c8 ignore next */
export function calculateTotal(items) {
// This SHOULD be tested!
return items.reduce((sum, item) => sum + item.price, 0);
}✅ Exception - Browser Automation / Integration Code:
Use /* c8 ignore start */ and /* c8 ignore stop */ for code that runs in browser context or requires complex integration setup:
// Browser automation (Playwright, Puppeteer)
/* c8 ignore start -- Browser automation code, tested through integration tests */
export async function fetchContent(url) {
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(url);
// Browser context code
const data = await page.evaluate(() => {
return document.querySelector('h1').innerText;
});
await browser.close();
return data;
}
/* c8 ignore stop */
// CLI entry points
/* c8 ignore start -- CLI entry point, tested through integration tests */
export async function main() {
// Parse args, handle I/O, etc.
const args = process.argv.slice(2);
// ... CLI logic
}
/* c8 ignore stop */When to use c8 ignore:
- Browser automation code (Playwright/Puppeteer page interactions)
- CLI entry points with process.exit() and argument parsing
- Code that runs in different contexts (browser vs Node.js)
- Complex integration points that require real dependencies
Requirements when using c8 ignore:
1. Extract testable logic: Move business logic into separate, testable functions 2. Create integration tests: Write integration test file (\.integration.test.js) to cover the ignored code 3. Add comment explaining why: `/ c8 ignore start -- Reason why and how it's tested /` 4. Minimize ignored code:* Keep ignored blocks as small as possible
✅ Instead - Refactor for testability:
// Extract business logic (testable)
export function processInput(data) {
return transform(data);
}
// Thin I/O wrapper
function main() {
const data = readInput();
const result = processInput(data); // Tested!
writeOutput(result);
}2. Separate I/O from Business Logic
❌ Untestable:
function main() {
process.stdin.on('data', (chunk) => {
// All logic mixed with I/O
const data = JSON.parse(chunk);
const result = complexProcessing(data);
writeToFile(result);
});
}✅ Testable:
export function processHookInput(input) {
const result = complexProcessing(input);
return result;
}
function main() {
process.stdin.on('data', (chunk) => {
const data = JSON.parse(chunk);
processHookInput(data); // Tested separately
});
}3. Export for Testing
export function main() {
if (process.argv.length !== 3) {
console.error('Usage: ...');
process.exit(1);
}
// ... logic
}
runIfMain(import.meta.url, main);4. Test All Branches
export function processFile(filePath) {
if (!filePath) throw new Error('Required'); // Branch 1
if (!fs.existsSync(filePath)) throw new Error('Not found'); // Branch 2
return fs.readFileSync(filePath); // Branch 3
}
// Test ALL branches
describe('processFile', () => {
test('missing path', () => expect(() => processFile()).toThrow('Required'));
test('not found', () => expect(() => processFile('x')).toThrow('Not found'));
test('exists', () => {
fs.writeFileSync('t.txt', 'c');
expect(processFile('t.txt').toString()).toBe('c');
fs.unlinkSync('t.txt');
});
});5. Test Error Paths
Test both success and error paths for every function:
export async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Fetch failed');
return await response.json();
} catch (error) {
console.error('Error:', error);
throw error;
}
}
// Test both paths
test('success', async () => {
global.fetch = vi.fn(() =>
Promise.resolve({
ok: true,
json: () => Promise.resolve({ data: 'test' }),
})
);
expect(await fetchData('url')).toEqual({ data: 'test' });
});
test('failure', async () => {
global.fetch = vi.fn(() => Promise.resolve({ ok: false }));
await expect(fetchData('url')).rejects.toThrow('Fetch failed');
});Test Organization
Arrange-Act-Assert
test('should calculate total', () => {
const items = [
{ price: 10, qty: 2 },
{ price: 5, qty: 3 },
]; // Arrange
const total = calculateTotal(items); // Act
expect(total).toBe(35); // Assert
});Descriptive Names
✅ test('should throw ValidationError when email invalid') ❌ test('works') or test('test1')
One Focus per Test
✅ Separate tests for status code, headers, body ❌ One test checking 10 different things
Test Cleanup
describe('file operations', () => {
const testDir = 'test_files';
beforeAll(() => fs.mkdirSync(testDir, { recursive: true }));
afterAll(() => fs.rmSync(testDir, { recursive: true, force: true }));
beforeEach(() => fs.writeFileSync(`${testDir}/temp.txt`, 'initial'));
afterEach(() => {
if (fs.existsSync(`${testDir}/temp.txt`)) {
fs.unlinkSync(`${testDir}/temp.txt`);
}
});
test('modifies file', () => {
modifyFile(`${testDir}/temp.txt`);
expect(fs.readFileSync(`${testDir}/temp.txt`, 'utf8')).toBe('modified');
});
});Running Tests
pnpm test # Run all tests
pnpm test:watch # Watch mode
pnpm test:coverage # With coverage
pnpm test script.test.js # Specific file
pnpm test --grep "pattern" # Match patternAdvanced Topics
See detailed guides:
[mocking-guide.md](mocking-guide.md) - Mocking patterns:
- Module/function/fs mocking
- process.exit(), process.argv, env vars
- Timers, Date, fetch/HTTP
- When to mock vs use real dependencies
[coverage-strategies.md](coverage-strategies.md) - 100% coverage:
- Refactoring I/O-heavy code
- Testing error paths
- Testing all branches
- Handling edge cases
Quick Reference
Common Pitfalls
❌ Don't:
1. Use coverage ignore comments 2. Skip error paths 3. Test implementation details 4. Over-mock (prefer real integrations) 5. Forget else branch 6. Assume code is untestable
✅ Do:
1. Separate I/O from logic 2. Test all branches/errors 3. Use real libs (JSDOM, etc.) 4. Clean up after tests 5. Descriptive names 6. One focus per test
Integration Testing
Prefer real dependencies:
import { JSDOM } from 'jsdom';
test('parses HTML', () => {
const dom = new JSDOM('<h1>Title</h1>');
const result = extractContent(dom.window.document);
expect(result.title).toBe('Title');
});Mock: External APIs, slow/destructive fs ops, timers, process.exit Use real: Pure JS libs, internal modules, data transforms, algorithms
Optimizing Integration Tests
When testing browser automation (Playwright/Puppeteer) or other slow integration points:
1. Combine related tests:
❌ Slow (9 tests, 17+ seconds):
it('should fetch content', async () => {
/* ... */
}, 2000);
it('should handle custom selectors', async () => {
/* ... */
}, 2000);
it('should handle custom timeouts', async () => {
/* ... */
}, 2000);
// Each launches a new browser✅ Fast (3 tests, <2 seconds):
it('should fetch content with custom options', async () => {
// Test multiple features in one browser launch
const result = await fetchContent(url, {
selector: 'article',
timeout: 5000,
});
expect(result).toContain('content');
expect(result).toContain('expected text');
expect(result).toMatch(/^# /); // markdown format
}, 10000);2. Make delays configurable:
// Auto-detect shorter delays for test environments
export async function fetchContent(url, options = {}) {
const { waitDelay = null } = options;
// file:// URLs need less wait time than remote sites
const defaultDelay = url.startsWith('file://') ? 500 : 2000;
const actualDelay = waitDelay !== null ? waitDelay : defaultDelay;
await page.waitForTimeout(actualDelay);
}3. Combine error scenarios:
it('should handle various error conditions', async () => {
await expect(fetchContent('invalid-url')).rejects.toThrow();
await expect(fetchContent('file:///not/found')).rejects.toThrow();
await expect(fetchContent(url, { timeout: 1 })).rejects.toThrow();
}, 20000);4. Use `c8 ignore` for browser automation:
/* c8 ignore start -- Browser automation, tested in integration tests */
export async function fetchContent(url) {
const browser = await chromium.launch();
// ... browser automation
await browser.close();
}
/* c8 ignore stop */Result: 8-10x faster test suites while maintaining full coverage and integration confidence.
Best Practices
1. Use Vitest (not Jest) 2. Import only vi (globals automatic) 3. Achieve 100% coverage for production 4. Refactor for testability; use c8 ignore only for browser automation/CLI code 5. Separate I/O from business logic 6. Test all branches and errors 7. Use real dependencies when possible 8. Write descriptive test names 9. Clean up after tests 10. One assertion focus per test 11. Optimize integration tests by combining related assertions
Coverage Strategies
Guide for achieving 100% test coverage without cheating.
Coverage Means
- Statements: 100% - Every statement executed
- Branches: 100% - Every if/else tested
- Functions: 100% - Every function called
- Lines: 100% - Every line executed
No exceptions. No coverage ignore comments.
Strategy 1: Refactor I/O-Heavy Code
Separate business logic from I/O operations.
Before - Untestable:
function main() {
process.stdin.on('data', (chunk) => {
const input = JSON.parse(chunk);
const result = complexProcessing(input);
writeToFile(formatOutput(result));
});
}After - Testable:
// Export testable logic
export function parseInput(chunk) {
return JSON.parse(chunk);
}
export function processData(input) {
return complexProcessing(input);
}
export function formatOutput(result) {
return format(result);
}
// Thin I/O wrapper
function main() {
process.stdin.on('data', (chunk) => {
const input = parseInput(chunk);
const result = processData(input);
const formatted = formatOutput(result);
saveOutput(formatted);
});
}Strategy 2: Test Error Paths
Every try-catch needs both success and error tests.
export function readConfig(filePath) {
try {
const content = fs.readFileSync(filePath, 'utf8');
return JSON.parse(content);
} catch (error) {
throw new Error(`Invalid config: ${filePath}`);
}
}
// Tests
test('success', () => {
vi.spyOn(fs, 'readFileSync').mockReturnValue('{"key":"value"}');
expect(readConfig('config.json')).toEqual({ key: 'value' });
});
test('file not found', () => {
vi.spyOn(fs, 'readFileSync').mockImplementation(() => {
throw new Error('ENOENT');
});
expect(() => readConfig('missing.json')).toThrow('Invalid config');
});
test('invalid JSON', () => {
vi.spyOn(fs, 'readFileSync').mockReturnValue('not json');
expect(() => readConfig('config.json')).toThrow('Invalid config');
});Strategy 3: Test All Branches
Every conditional creates branches.
export function classifyValue(value) {
if (value === null || value === undefined) return 'null-ish'; // 1
if (typeof value !== 'number') return 'non-number'; // 2
if (value < 0) return 'negative'; // 3
if (value === 0) return 'zero'; // 4
if (value < 10) return 'small'; // 5
return 'large'; // 6
}
// Test ALL 6 branches
test('null-ish', () => {
expect(classifyValue(null)).toBe('null-ish');
expect(classifyValue(undefined)).toBe('null-ish');
});
test('non-number', () => expect(classifyValue('x')).toBe('non-number'));
test('negative', () => expect(classifyValue(-1)).toBe('negative'));
test('zero', () => expect(classifyValue(0)).toBe('zero'));
test('small', () => expect(classifyValue(5)).toBe('small'));
test('large', () => expect(classifyValue(20)).toBe('large'));Strategy 4: Test Logical Operators
Logical operators (&&, ||) create branches.
export function isValid(value) {
return value && value.length > 0;
}
// All branches
test('valid non-empty', () => expect(isValid('test')).toBe(true));
test('valid empty', () => expect(isValid('')).toBe(false));
test('null/undefined', () => {
expect(isValid(null)).toBe(false);
expect(isValid(undefined)).toBe(false);
});Strategy 5: Mock process.exit()
export function main(args) {
if (args.length === 0) {
console.error('Usage: script.js <file>');
process.exit(1);
}
if (!fs.existsSync(args[0])) {
console.error('File not found');
process.exit(1);
}
processFile(args[0]);
process.exit(0);
}
// Tests
let mockExit;
beforeEach(
() => (mockExit = vi.spyOn(process, 'exit').mockImplementation(() => {}))
);
afterEach(() => mockExit.mockRestore());
test('no args', () => {
main([]);
expect(mockExit).toHaveBeenCalledWith(1);
});
test('file not found', () => {
vi.spyOn(fs, 'existsSync').mockReturnValue(false);
main(['missing.txt']);
expect(mockExit).toHaveBeenCalledWith(1);
});
test('success', () => {
vi.spyOn(fs, 'existsSync').mockReturnValue(true);
vi.spyOn(global, 'processFile').mockImplementation(() => {});
main(['file.txt']);
expect(mockExit).toHaveBeenCalledWith(0);
});Strategy 6: Test Switch Statements
Every case including default must be tested.
export function getStatus(code) {
switch (code) {
case 200:
return 'success';
case 404:
return 'not found';
case 500:
return 'server error';
default:
return 'unknown';
}
}
test('200', () => expect(getStatus(200)).toBe('success'));
test('404', () => expect(getStatus(404)).toBe('not found'));
test('500', () => expect(getStatus(500)).toBe('server error'));
test('other', () => expect(getStatus(999)).toBe('unknown'));Strategy 7: Test Ternary Operators
export function getLabel(value) {
return value ? 'yes' : 'no';
}
test('truthy', () => expect(getLabel('x')).toBe('yes'));
test('falsy', () => expect(getLabel('')).toBe('no'));Strategy 8: Test Early Returns
export function validate(data) {
if (!data) return { valid: false, error: 'Missing data' };
if (!data.email) return { valid: false, error: 'Missing email' };
if (!data.email.includes('@'))
return { valid: false, error: 'Invalid email' };
return { valid: true };
}
test('missing data', () => {
expect(validate(null).error).toBe('Missing data');
});
test('missing email', () => {
expect(validate({}).error).toBe('Missing email');
});
test('invalid email', () => {
expect(validate({ email: 'x' }).error).toBe('Invalid email');
});
test('valid', () => {
expect(validate({ email: 'a@b.c' }).valid).toBe(true);
});Strategy 9: Test Async Error Handling
export async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error('User not found');
return await response.json();
} catch (error) {
console.error('Failed:', error);
throw error;
}
}
test('success', async () => {
global.fetch = vi.fn(() =>
Promise.resolve({ ok: true, json: async () => ({ id: 1 }) })
);
expect(await fetchUser(1)).toEqual({ id: 1 });
});
test('404', async () => {
global.fetch = vi.fn(() => Promise.resolve({ ok: false }));
await expect(fetchUser(1)).rejects.toThrow('User not found');
});
test('network error', async () => {
global.fetch = vi.fn(() => Promise.reject(new Error('Network')));
await expect(fetchUser(1)).rejects.toThrow('Network');
});Strategy 10: Test Optional Chaining
export function getEmail(user) {
return user?.email || 'no-email';
}
test('with email', () => {
expect(getEmail({ email: 'a@b.c' })).toBe('a@b.c');
});
test('without email', () => expect(getEmail({})).toBe('no-email'));
test('null user', () => expect(getEmail(null)).toBe('no-email'));Common Coverage Gaps
Gap 1: Forgot else
export function check(value) {
if (value > 0) return 'positive';
// Missing test for value <= 0
}Gap 2: Forgot error path
export function parse(json) {
try {
return JSON.parse(json);
} catch (error) {
return null; // Missing test
}
}Gap 3: Forgot default case
export function handle(type) {
switch (type) {
case 'A':
return 'a';
default:
return 'unknown'; // Missing test
}
}Gap 4: Forgot second condition
export function validate(a, b) {
if (a && b) return true;
return false;
// Need tests for: a=T,b=F and a=F,b=T
}Checking Coverage
pnpm test:coverage
# Must show 100% for all metricsIf not 100%:
1. Open coverage/index.html 2. Find uncovered lines (red) 3. Identify missing branch/path 4. Write test for that case 5. Re-run coverage
Refactoring Checklist
When code seems untestable:
- [ ] Separate I/O from business logic
- [ ] Extract pure functions
- [ ] Make dependencies injectable
- [ ] Avoid global state
- [ ] Export internal functions
- [ ] Break down large functions
100% Coverage Without Cheating
Never use:
/* istanbul ignore next *//* c8 ignore next *//* c8 ignore start */.../* c8 ignore stop */
Instead:
1. Refactor code to be testable 2. Mock external dependencies 3. Test all branches explicitly 4. Use integration tests for I/O
Complete Example
// hook-processor.js
export function processHookData(data) {
if (!data) throw new Error('Data required');
if (!data.tool) throw new Error('Tool required');
return { tool: data.tool, timestamp: Date.now(), processed: true };
}
export function saveToLog(data) {
fs.appendFileSync('log.json', JSON.stringify(data) + '\n');
}
function main() {
process.stdin.on('data', (chunk) => {
try {
const input = JSON.parse(chunk.toString());
const processed = processHookData(input);
saveToLog(processed);
} catch (error) {
console.error('Error:', error.message);
process.exit(1);
}
});
}Tests - 100% coverage:
describe('processHookData', () => {
test('valid', () => {
const result = processHookData({ tool: 'Read' });
expect(result.tool).toBe('Read');
expect(result.processed).toBe(true);
});
test('no data', () => {
expect(() => processHookData(null)).toThrow('Data required');
});
test('no tool', () => {
expect(() => processHookData({})).toThrow('Tool required');
});
});
describe('saveToLog', () => {
afterEach(() => vi.restoreAllMocks());
test('appends to log', () => {
const spy = vi.spyOn(fs, 'appendFileSync').mockImplementation(() => {});
saveToLog({ tool: 'Read', timestamp: 12345 });
expect(spy).toHaveBeenCalled();
});
});Result: 100% statements, branches, functions, lines.
Mocking with Vitest
Complete guide for mocking patterns with Vitest.
Basic Mocking
import { vi } from 'vitest';
const mockFn = vi.fn();
mockFn.mockReturnValue(42);
mockFn.mockImplementation((x) => x * 2);
mockFn.mockResolvedValue({ data: 'test' });
mockFn.mockRejectedValue(new Error('Failed'));Module Mocking
import { vi } from 'vitest';
// Mock entire module
vi.mock('child_process', () => ({
execSync: vi.fn(() => 'mocked output'),
}));
const { execSync } = await import('child_process');
test('uses mocked execSync', () => {
expect(execSync('command')).toBe('mocked output');
});Partial Module Mocking
// Mock only specific exports
vi.mock('fs', async () => {
const actual = await vi.importActual('fs');
return {
...actual,
readFileSync: vi.fn(() => 'mocked'),
};
});Mocking fs Operations
import { vi } from 'vitest';
import fs from 'fs';
describe('file operations', () => {
afterEach(() => vi.restoreAllMocks());
test('reads file', () => {
vi.spyOn(fs, 'readFileSync').mockReturnValue('mocked');
vi.spyOn(fs, 'existsSync').mockReturnValue(true);
expect(fs.readFileSync('file.txt')).toBe('mocked');
});
test('handles errors', () => {
vi.spyOn(fs, 'readFileSync').mockImplementation(() => {
throw new Error('ENOENT');
});
expect(() => readFile('missing.txt')).toThrow('ENOENT');
});
});Mocking process.exit()
describe('CLI', () => {
let mockExit;
beforeEach(() => {
mockExit = vi.spyOn(process, 'exit').mockImplementation(() => {});
});
afterEach(() => mockExit.mockRestore());
test('exits with code 1 on error', () => {
runCLI(['invalid']);
expect(mockExit).toHaveBeenCalledWith(1);
});
});Mocking process.argv
describe('argument parsing', () => {
let originalArgv;
beforeEach(() => (originalArgv = process.argv));
afterEach(() => (process.argv = originalArgv));
test('parses arguments', () => {
process.argv = ['node', 'script.js', '--verbose', 'input.txt'];
const args = parseArgs();
expect(args.verbose).toBe(true);
});
});Mocking Environment Variables
describe('environment config', () => {
let originalEnv;
beforeEach(() => (originalEnv = { ...process.env }));
afterEach(() => (process.env = originalEnv));
test('uses env variable', () => {
process.env.API_KEY = 'test-key';
expect(loadConfig().apiKey).toBe('test-key');
});
test('throws when missing', () => {
delete process.env.API_KEY;
expect(() => loadConfig()).toThrow('API_KEY is required');
});
});Mocking Timers
describe('time-dependent', () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
test('calls callback after delay', () => {
const callback = vi.fn();
setTimeout(callback, 1000);
expect(callback).not.toHaveBeenCalled();
vi.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalledOnce();
});
test('interval multiple times', () => {
const callback = vi.fn();
setInterval(callback, 100);
vi.advanceTimersByTime(350);
expect(callback).toHaveBeenCalledTimes(3);
});
});Mocking Date
describe('date-dependent', () => {
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
test('formats current date', () => {
vi.setSystemTime(new Date('2024-01-15T10:00:00Z'));
expect(formatCurrentDate()).toBe('2024-01-15');
});
test('checks expiration', () => {
vi.setSystemTime(new Date('2024-01-15'));
const token = { expiresAt: new Date('2024-01-10') };
expect(isExpired(token)).toBe(true);
});
});Mocking fetch/HTTP
describe('API calls', () => {
beforeEach(() => (global.fetch = vi.fn()));
afterEach(() => vi.restoreAllMocks());
test('fetches user data', async () => {
global.fetch.mockResolvedValue({
ok: true,
json: async () => ({ id: 1, name: 'John' }),
});
const user = await fetchUser(1);
expect(user).toEqual({ id: 1, name: 'John' });
});
test('handles network error', async () => {
global.fetch.mockRejectedValue(new Error('Network error'));
await expect(fetchUser(1)).rejects.toThrow('Network error');
});
test('handles HTTP error', async () => {
global.fetch.mockResolvedValue({ ok: false, status: 404 });
await expect(fetchUser(1)).rejects.toThrow('User not found');
});
});Spy vs Mock vs Stub
Spy: Watch real function
const spy = vi.spyOn(obj, 'method');
obj.method(); // Calls real implementation
expect(spy).toHaveBeenCalled();Mock: Replace implementation
const mock = vi.spyOn(obj, 'method').mockReturnValue('mocked');
obj.method(); // Returns 'mocked'Stub: Mock with no implementation
const stub = vi.fn();
stub(); // Returns undefinedMock Assertions
const mockFn = vi.fn();
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledTimes(3);
expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2');
expect(mockFn).toHaveBeenLastCalledWith('lastArg');
expect(mockFn).toHaveBeenNthCalledWith(2, 'secondCall');Cleaning Up Mocks
describe('suite', () => {
afterEach(() => {
vi.restoreAllMocks(); // Restore original implementations
vi.clearAllMocks(); // Clear call history
vi.resetAllMocks(); // Clear history + reset implementations
});
});Differences:
restoreAllMocks(): Restores originalsclearAllMocks(): Clears history, keeps mocksresetAllMocks(): Clears history + resets
When to Mock vs Real
Mock:
- External APIs (HTTP, database)
- Slow/destructive fs operations
- process.exit() (prevents termination)
- Date.now(), timers (deterministic)
- External services (email, payments)
- Random generation (reproducible)
Use Real:
- Pure JS libraries (lodash, date-fns)
- JSDOM for HTML parsing
- Internal modules/utilities
- Data transformations
- Simple helpers
Best Practices
1. Keep mocks simple - No complex implementations 2. Mock at boundaries - External deps, not internal logic 3. Clean up - Always restore in afterEach 4. Avoid over-mocking - Too many = testing mocks, not code 5. Use spies when possible - Spy on real over replacing 6. Document why - Comment why mocked
Common Mistakes
❌ Don't mock everything
vi.mock('./helper1');
vi.mock('./helper2');
vi.mock('./helper3');
// Now testing mocks, not real code❌ Don't mock implementation details
const spy = vi.spyOn(obj, '_privateMethod');
obj.publicMethod();
expect(spy).toHaveBeenCalled(); // Brittle!❌ Don't forget to restore
test('with mock', () => {
vi.spyOn(fs, 'readFileSync').mockReturnValue('test');
// Forgot restore - next test uses mock
});✅ Do mock externals
global.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ data: 'test' }),
});✅ Do restore in afterEach
afterEach(() => vi.restoreAllMocks());