Jest testing patterns — test structure, mocking, async testing, snapshot
99
99%
Does it follow best practices?
Impact
99%
1.26xAverage score across 6 eval scenarios
Passed
No known issues
The platform team has built a RateLimiter utility that enforces a maximum number of function calls per time window. When the limit is exceeded, calls are queued and executed in batches once the window resets. The limiter uses setTimeout internally to schedule the window reset and flush the queue.
The existing implementation has no test coverage and has caused production incidents due to subtle timing bugs. The engineering team needs a thorough test suite that verifies the limiter's behavior at boundary conditions — exactly at the limit, one over the limit, and after the window resets — without the tests actually waiting for real time to pass.
Write a complete Jest test file at src/utils/__tests__/rateLimiter.test.ts.
Tests should cover at minimum:
src/utils/rateLimiter.tsexport class RateLimiter {
private callCount = 0;
private queue: Array<() => void> = [];
constructor(
private readonly maxCalls: number,
private readonly windowMs: number
) {
this.scheduleReset();
}
execute(fn: () => void): void {
if (this.callCount < this.maxCalls) {
this.callCount++;
fn();
} else {
this.queue.push(fn);
}
}
private scheduleReset(): void {
setTimeout(() => {
this.callCount = 0;
const toFlush = this.queue.splice(0, this.maxCalls);
toFlush.forEach((fn) => {
this.callCount++;
fn();
});
this.scheduleReset();
}, this.windowMs);
}
}