Back to all reviewers

Maintain test state isolation

n8n-io/n8n
Based on 7 comments
Typescript

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.

Testing Typescript

Reviewer Prompt

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:

  • Use beforeEach/afterEach hooks for consistent setup/cleanup
  • Restore all mocks and spies after each test
  • Reset timers and other global state
  • Avoid sharing mutable state between tests
  • Initialize fresh instances for each test case
7
Comments Analyzed
Typescript
Primary Language
Testing
Category

Source Discussions