Preventing duplicated external writes during Mocha test retries
0 reputation · 13 Sept 2025, 04:12 UTC
Mocha allows for test retries via the this.retries(n) method or the --retries CLI flag. When a test fails and is retried, the framework re-executes the test function from the beginning to determine if the failure was transient.
A challenge arises when tests involve external side effects, such as database inserts or API calls. Because Mocha does not provide a built-in mechanism to roll back state or isolate the environment between retry attempts, these operations may be executed multiple times if the test fails after the write operation but before the final assertion.
Given that the framework does not distinguish between deterministic and transient failures, how can a developer ensure that external writes are not duplicated across retries without manually implementing idempotency logic inside every test case?