timers.tick(milliseconds)


提前所有模拟定时器的时间。

¥Advances time for all mocked timers.

  • milliseconds <number> 定时器提前的时间量(以毫秒为单位)。

    ¥milliseconds <number> The amount of time, in milliseconds, to advance the timers.

注意:这与 Node.js 中 setTimeout 的行为不同,它只接受正数。在 Node.js 中,仅出于 Web 兼容性原因才支持带有负数的 setTimeout

¥Note: This diverges from how setTimeout in Node.js behaves and accepts only positive numbers. In Node.js, setTimeout with negative numbers is only supported for web compatibility reasons.

以下示例模拟 setTimeout 函数,并通过使用 .tick 时间提前来触发所有挂起的定时器。

¥The following example mocks a setTimeout function and by using .tick advances in time triggering all pending timers.

import assert from 'node:assert';
import { test } from 'node:test';

test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
  const fn = context.mock.fn();

  context.mock.timers.enable(['setTimeout']);

  setTimeout(fn, 9999);

  assert.strictEqual(fn.mock.callCount(), 0);

  // Advance in time
  context.mock.timers.tick(9999);

  assert.strictEqual(fn.mock.callCount(), 1);
});const assert = require('node:assert');
const { test } = require('node:test');

test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
  const fn = context.mock.fn();
  context.mock.timers.enable(['setTimeout']);

  setTimeout(fn, 9999);
  assert.strictEqual(fn.mock.callCount(), 0);

  // Advance in time
  context.mock.timers.tick(9999);

  assert.strictEqual(fn.mock.callCount(), 1);
});

或者,.tick 函数可以被调用多次

¥Alternativelly, the .tick function can be called many times

import assert from 'node:assert';
import { test } from 'node:test';

test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
  const fn = context.mock.fn();
  context.mock.timers.enable(['setTimeout']);
  const nineSecs = 9000;
  setTimeout(fn, nineSecs);

  const twoSeconds = 3000;
  context.mock.timers.tick(twoSeconds);
  context.mock.timers.tick(twoSeconds);
  context.mock.timers.tick(twoSeconds);

  assert.strictEqual(fn.mock.callCount(), 1);
});const assert = require('node:assert');
const { test } = require('node:test');

test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
  const fn = context.mock.fn();
  context.mock.timers.enable(['setTimeout']);
  const nineSecs = 9000;
  setTimeout(fn, nineSecs);

  const twoSeconds = 3000;
  context.mock.timers.tick(twoSeconds);
  context.mock.timers.tick(twoSeconds);
  context.mock.timers.tick(twoSeconds);

  assert.strictEqual(fn.mock.callCount(), 1);
});