Tests must be isolated and not leak state between runs. This includes properly cleaning up mocks, spies, and any global state modifications to ensure reliable and maintainable test suites.

Key practices:

Example of proper cleanup:

describe("dialog helpers", () => {
  let originalStdoutColumns: number;

  beforeAll(() => {
    originalStdoutColumns = process.stdout.columns;
  });

  afterEach(() => {
    process.stdout.columns = originalStdoutColumns;
  });

  test("with lines truncated", async () => {
    process.stdout.columns = 40;
    // test logic here
  });
});

This prevents test pollution where one test’s modifications affect subsequent tests, leading to flaky or unreliable test results.