Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/runtime/cron.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ job.ref(); // keep the process alive (default)

### Fake timers

In-process cron honors `jest.useFakeTimers()`. `setSystemTime()`, `advanceTimersByTime()`, and `runAllTimers()` control when it fires, so you can test scheduled callbacks without waiting on the real clock.
In-process cron honors `jest.useFakeTimers()`. `setSystemTime()`, `advanceTimersByTime()`, and `runOnlyPendingTimers()` control when it fires, so you can test scheduled callbacks without waiting on the real clock. Because a cron job re-arms itself after every fire, `jest.runAllTimers()` will hit the `timerLimit` cap (default 100000) and throw; use `advanceTimersByTime()` or `runOnlyPendingTimers()` instead.

---

Expand Down
9 changes: 8 additions & 1 deletion packages/bun-types/test.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,14 @@ declare module "bun:test" {
function fn<T extends (...args: any[]) => any>(func?: T): Mock<T>;
function setSystemTime(now?: number | Date): void;
function setTimeout(milliseconds: number): void;
function useFakeTimers(options?: { now?: number | Date }): typeof vi;
function useFakeTimers(options?: {
now?: number | Date;
/**
* Maximum number of timers `runAllTimers()` will run before throwing an
* "assuming an infinite loop" error. Defaults to 100000.
*/
timerLimit?: number;
}): typeof vi;
function useRealTimers(): typeof vi;
function advanceTimersByTime(milliseconds: number): typeof vi;
function advanceTimersToNextTimer(): typeof vi;
Expand Down
48 changes: 43 additions & 5 deletions src/runtime/test_runner/timers/FakeTimers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,19 @@ unsafe extern "C" {
#[derive(Default)]
pub struct FakeTimers {
active: bool,
/// Jest's `timerLimit`: maximum recursive timers `runAllTimers()` will drain
/// before throwing. Set by `useFakeTimers({ timerLimit })`; defaults to
/// `DEFAULT_TIMER_LIMIT` on every activation.
timer_limit: u32,
/// The sorted fake timers. TimerHeap is not optimal here because we need these operations:
/// - peek/takeFirst (provided by TimerHeap)
/// - peekLast (cannot be implemented efficiently with TimerHeap)
/// - count (cannot be implemented efficiently with TimerHeap)
pub timers: TimerHeap,
}

const DEFAULT_TIMER_LIMIT: u32 = 100_000;

// `date_now_offset` is stored as `AtomicU64` (f64 bits) so the static is `Sync`
// without `static mut`.
pub struct CurrentTime {
Expand Down Expand Up @@ -119,8 +125,9 @@ impl FakeTimers {
self.active
}

fn activate(&mut self, js_now: f64, global: &JSGlobalObject) {
fn activate(&mut self, js_now: f64, timer_limit: u32, global: &JSGlobalObject) {
self.active = true;
self.timer_limit = timer_limit;
CURRENT_TIME.set(global, &Timespec::EPOCH, Some(js_now));
}

Expand Down Expand Up @@ -222,8 +229,24 @@ impl FakeTimers {
Self::execute_until(global, until);
}

fn execute_all_timers(global: &JSGlobalObject) {
while Self::execute_next(global) {}
fn execute_all_timers(global: &JSGlobalObject) -> JsResult<()> {
// Jest caps runAllTimers() so a self-re-arming timer (setInterval,
// Bun.cron) can't spin the drain loop forever.
let all = timer_all();
// SAFETY: per-thread `timer::All`, live for the VM lifetime.
let limit = unsafe { (*all).fake_timers.timer_limit };
for _ in 0..limit {
if !Self::execute_next(global) {
return Ok(());
}
}
// SAFETY: as above; borrow ends at this statement.
if unsafe { (*all).fake_timers.timers.peek() }.is_none() {
return Ok(());
}
Err(global.throw(format_args!(
"Aborting after running {limit} timers, assuming an infinite loop!"
)))
}
}

Expand Down Expand Up @@ -268,6 +291,7 @@ fn set_fake_timer_marker(global: &JSGlobalObject, enabled: bool) {
fn use_fake_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
// SAFETY: FFI call into C++ JSMock
let mut js_now = JSMock__getCurrentUnixTimeMs();
let mut timer_limit = DEFAULT_TIMER_LIMIT;

// Check if options object was provided
let args = frame.arguments_as_array::<1>();
Expand All @@ -289,10 +313,24 @@ fn use_fake_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSVal
)));
}
}
if let Some(limit) = options_value.get(global, "timerLimit")? {
if !limit.is_number() {
return Err(global.throw_invalid_arguments(format_args!(
"'timerLimit' must be a positive integer"
)));
}
let n = limit.as_number();
if !n.is_finite() || n < 1.0 || n > u32::MAX as f64 || n.trunc() != n {
return Err(global.throw_invalid_arguments(format_args!(
"'timerLimit' must be a positive integer"
)));
}
timer_limit = n as u32;
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}

// SAFETY: per-thread `timer::All`; `activate` does not re-enter `All`.
unsafe { (*timer_all()).fake_timers.activate(js_now, global) };
unsafe { (*timer_all()).fake_timers.activate(js_now, timer_limit, global) };

// Set setTimeout.clock = true to signal that fake timers are enabled.
// This is used by testing-library/react to detect if jest.advanceTimersByTime should be called.
Expand Down Expand Up @@ -373,7 +411,7 @@ fn run_only_pending_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResu
fn run_all_timers(global: &JSGlobalObject, frame: &CallFrame) -> JsResult<JSValue> {
error_unless_fake_timers(global)?;

FakeTimers::execute_all_timers(global);
FakeTimers::execute_all_timers(global)?;

Ok(frame.this())
}
Expand Down
81 changes: 81 additions & 0 deletions test/js/bun/test/fake-timers/fake-timers.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { bunEnv, bunExe } from "harness";
import { afterEach, describe, expect, test, vi } from "vitest";

afterEach(() => vi.useRealTimers());
Expand Down Expand Up @@ -161,6 +162,86 @@ describe("runAllTimers", () => {
vi.runAllTimers();
expect(order.takeOrderMessages()).toEqual(["9", "10", "14", "20"]);
});

// Without the iteration cap these spin at 100% CPU forever, so run each in a
// subprocess with a spawn-side timeout as the fail-before guard.
async function runAllTimersFixture(options: string, setup: string) {
const src = `
const { jest } = require("bun:test");
jest.useFakeTimers(${options});
let fires = 0;
${setup}
try {
jest.runAllTimers();
console.log(JSON.stringify({ threw: false, fires }));
} catch (e) {
console.log(JSON.stringify({ threw: true, message: String(e.message), fires }));
}
stop();
jest.useRealTimers();
`;
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", src],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
timeout: 10_000,
killSignal: "SIGKILL",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
return { stdout, stderr, exitCode, signalCode: proc.signalCode };
}

test.concurrent.each([
["setInterval", `const id = setInterval(() => fires++, 10); const stop = () => clearInterval(id);`],
[
"recursive setTimeout",
`const tick = () => { fires++; setTimeout(tick, 10); }; setTimeout(tick, 10); const stop = () => {};`,
],
["Bun.cron", `const job = Bun.cron("* * * * *", () => fires++); const stop = () => job.stop();`],
])("aborts with an error when %s re-arms forever", async (_name, setup) => {
const { stdout, stderr, exitCode, signalCode } = await runAllTimersFixture("{ timerLimit: 50 }", setup);
expect({ stdout, signalCode, stderr }).toEqual({
stdout:
JSON.stringify({
threw: true,
message: "Aborting after running 50 timers, assuming an infinite loop!",
fires: 50,
}) + "\n",
signalCode: null,
stderr: expect.not.stringContaining("error:"),
});
expect(exitCode).toBe(0);
});

test.concurrent.each([
["below", 5],
["at", 50],
])("does not abort when the chain terminates %s the limit", async (_where, n) => {
const setup = `
let remaining = ${n};
const tick = () => { fires++; if (--remaining > 0) setTimeout(tick, 10); };
setTimeout(tick, 10);
const stop = () => {};
`;
const { stdout, stderr, exitCode, signalCode } = await runAllTimersFixture("{ timerLimit: 50 }", setup);
expect({ stdout, signalCode, stderr }).toEqual({
stdout: JSON.stringify({ threw: false, fires: n }) + "\n",
signalCode: null,
stderr: expect.not.stringContaining("error:"),
});
expect(exitCode).toBe(0);
});

test("timerLimit validation", () => {
for (const bad of [0, -1, 1.5, NaN, Infinity, "ten", {}]) {
expect(() => vi.useFakeTimers({ timerLimit: bad as any })).toThrow("'timerLimit' must be a positive integer");
}
expect(() => vi.useFakeTimers({ timerLimit: undefined })).not.toThrow();
vi.useRealTimers();
expect(() => vi.useFakeTimers({ timerLimit: 1 })).not.toThrow();
vi.useRealTimers();
});
});
describe("getTimerCount", () => {
test("returns correct count of pending timers", () => {
Expand Down
Loading