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.
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:
restoreMocks: true
in Vitest config)afterEach
hooksexpect()
inside mocks to improve debuggabilityExample 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.
Enter the URL of a public GitHub repository