|
| 1 | +--- |
| 2 | +description: Vitest usage guide |
| 3 | +globs: **/*.test.ts |
| 4 | +--- |
| 5 | + # Vitest Usage Guide |
| 6 | + |
| 7 | +## Basic Test Structure |
| 8 | + |
| 9 | +Tests are organized following these patterns: |
| 10 | + |
| 11 | +~~~typescript |
| 12 | +import { beforeEach, describe, expect, test, vi } from 'vitest'; |
| 13 | + |
| 14 | +describe('Component/Feature Name', () => { |
| 15 | + // Setup and teardown |
| 16 | + beforeEach(() => { |
| 17 | + vi.clearAllMocks(); |
| 18 | + }); |
| 19 | + |
| 20 | + describe('Specific Aspect', () => { |
| 21 | + test('should do something specific', () => { |
| 22 | + // Test implementation |
| 23 | + }); |
| 24 | + }); |
| 25 | +}); |
| 26 | +~~~ |
| 27 | + |
| 28 | +## Mocking Patterns |
| 29 | + |
| 30 | +### Module Mocking |
| 31 | + |
| 32 | +1. **Hoisted Mocks**: Use `vi.hoisted()` for mocks needed across multiple tests: |
| 33 | +~~~typescript |
| 34 | +const mocks = vi.hoisted(() => ({ |
| 35 | + registerCleanup: vi.fn(), |
| 36 | + getDirName: vi.fn(), |
| 37 | +})); |
| 38 | + |
| 39 | +vi.mock('#utils/cleanup.js', () => ({ |
| 40 | + registerCleanup: mocks.registerCleanup, |
| 41 | +})); |
| 42 | +~~~ |
| 43 | + |
| 44 | +2. **Partial Module Mocks**: Keep original functionality while mocking specific exports: |
| 45 | +~~~typescript |
| 46 | +vi.mock('node:fs', () => ({ |
| 47 | + ...vi.importActual('node:fs'), |
| 48 | + readFileSync: vi.fn((path) => { |
| 49 | + // Custom implementation |
| 50 | + }), |
| 51 | +})); |
| 52 | +~~~ |
| 53 | + |
| 54 | +3. **External Module Mocks**: Mock external dependencies: |
| 55 | +~~~typescript |
| 56 | +vi.mock('vite', () => ({ |
| 57 | + createServer: vi.fn(), |
| 58 | +})); |
| 59 | +~~~ |
| 60 | + |
| 61 | +### Mock Implementations |
| 62 | + |
| 63 | +1. **Mock Classes**: Create mock implementations for complex objects: |
| 64 | +~~~typescript |
| 65 | +class MockWebSocketServer extends EventEmitter { |
| 66 | + clients = new Set(); |
| 67 | + close = vi.fn().mockResolvedValue(undefined); |
| 68 | + // ... other methods |
| 69 | +} |
| 70 | +~~~ |
| 71 | + |
| 72 | +2. **Mock Functions**: Use `vi.fn()` with specific implementations: |
| 73 | +~~~typescript |
| 74 | +const mockFn = vi.fn() |
| 75 | + .mockReturnValue(defaultValue) |
| 76 | + .mockImplementation((arg) => { |
| 77 | + // Custom implementation |
| 78 | + }); |
| 79 | +~~~ |
| 80 | + |
| 81 | +3. **Async Mocks**: Handle promises in mocks: |
| 82 | +~~~typescript |
| 83 | +mockFunction.mockResolvedValue(value); // for Promise.resolve |
| 84 | +mockFunction.mockRejectedValue(error); // for Promise.reject |
| 85 | +~~~ |
| 86 | + |
| 87 | +## Testing Patterns |
| 88 | + |
| 89 | +### Cleanup and Reset |
| 90 | + |
| 91 | +1. **Clear Mocks**: Reset all mocks before each test: |
| 92 | +~~~typescript |
| 93 | +beforeEach(() => { |
| 94 | + vi.clearAllMocks(); |
| 95 | +}); |
| 96 | +~~~ |
| 97 | + |
| 98 | +2. **Mock Reset**: Reset specific mocks: |
| 99 | +~~~typescript |
| 100 | +mockFunction.mockClear(); // Clear usage data |
| 101 | +mockFunction.mockReset(); // Clear usage and implementation |
| 102 | +mockFunction.mockRestore(); // Restore original implementation |
| 103 | +~~~ |
| 104 | + |
| 105 | +### Assertions |
| 106 | + |
| 107 | +1. **Function Calls**: |
| 108 | +~~~typescript |
| 109 | +expect(mockFn).toHaveBeenCalled(); |
| 110 | +expect(mockFn).toHaveBeenCalledWith(expect.any(Function)); |
| 111 | +expect(mockFn).toHaveBeenCalledTimes(1); |
| 112 | +~~~ |
| 113 | + |
| 114 | +2. **Objects and Values**: |
| 115 | +~~~typescript |
| 116 | +expect(result).toBe(value); // Strict equality |
| 117 | +expect(object).toEqual(expected); // Deep equality |
| 118 | +expect(object).toMatchObject(partial); // Partial object match |
| 119 | +~~~ |
| 120 | + |
| 121 | +3. **Async Tests**: |
| 122 | +~~~typescript |
| 123 | +await expect(asyncFn()).rejects.toThrow('error message'); |
| 124 | +await expect(asyncFn()).resolves.toBe(value); |
| 125 | +~~~ |
| 126 | + |
| 127 | +### Event Testing |
| 128 | + |
| 129 | +1. **Event Emitters**: |
| 130 | +~~~typescript |
| 131 | +mockServer.emit('connection', mockClient, { url: '?source=test' }); |
| 132 | +expect(mockClient.send).toHaveBeenCalledWith( |
| 133 | + expect.stringContaining('"event":"client_list"') |
| 134 | +); |
| 135 | +~~~ |
| 136 | + |
| 137 | +2. **Error Events**: |
| 138 | +~~~typescript |
| 139 | +await expect( |
| 140 | + () => new Promise((_, reject) => { |
| 141 | + server.on('error', reject); |
| 142 | + server.emit('error', new Error('Test error')); |
| 143 | + }) |
| 144 | +).rejects.toThrow('Expected error'); |
| 145 | +~~~ |
| 146 | + |
| 147 | +## Best Practices |
| 148 | + |
| 149 | +1. **Organize Tests**: Group related tests using nested `describe` blocks |
| 150 | +2. **Mock Isolation**: Use `beforeEach` to reset mocks and state |
| 151 | +3. **Type Safety**: Maintain type safety in mocks using TypeScript interfaces |
| 152 | +4. **Error Cases**: Test both success and error scenarios |
| 153 | +5. **Clear Descriptions**: Use descriptive test names that explain the expected behavior |
| 154 | +6. **Avoid Test Interdependence**: Each test should be independent and not rely on other tests |
| 155 | + |
| 156 | +## Common Gotchas |
| 157 | + |
| 158 | +1. **Async Cleanup**: Always handle async cleanup in tests |
| 159 | +2. **Mock Scope**: Be aware of mock hoisting and scoping rules |
| 160 | +3. **Event Order**: Consider event timing in async tests |
| 161 | +4. **Type Assertions**: Use proper type assertions for mocked objects |
| 162 | +5. **Promise Handling**: Always await promises in async tests |
| 163 | +~~~ |
0 commit comments