Ensure each test runs in isolation by properly managing test state, mocks, and timers. Clean up all test artifacts in beforeEach/afterEach hooks rather than within individual tests to prevent state leakage and test interdependence.
Ensure each test runs in isolation by properly managing test state, mocks, and timers. Clean up all test artifacts in beforeEach/afterEach hooks rather than within individual tests to prevent state leakage and test interdependence.
Example:
describe('MyComponent', () => {
// โ Bad: Global mock without cleanup
const globalMock = vi.spyOn(global, 'setTimeout');
// โ
Good: Proper setup and cleanup
let timeoutSpy: SpyInstance;
beforeEach(() => {
timeoutSpy = vi.spyOn(global, 'setTimeout');
});
afterEach(() => {
vi.restoreAllMocks();
vi.useRealTimers();
});
it('should handle timeouts', () => {
vi.useFakeTimers();
// Test implementation
});
});
Key practices:
Enter the URL of a public GitHub repository