日期和定时器一起工作


¥Dates and Timers working together

日期和定时器对象相互依赖。如果使用 setTime() 将当前时间传递给模拟的 Date 对象,则使用 setTimeoutsetInterval 设置的定时器不会受到影响。

¥Dates and timer objects are dependent on each other. If you use setTime() to pass the current time to the mocked Date object, the set timers with setTimeout and setInterval will not be affected.

但是,tick 方法将推进模拟的 Date 对象。

¥However, the tick method will advanced the mocked Date object.

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

test('runAll functions following the given order', (context) => {
  context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
  const results = [];
  setTimeout(() => results.push(1), 9999);

  assert.deepStrictEqual(results, []);
  context.mock.timers.setTime(12000);
  assert.deepStrictEqual(results, []);
  // The date is advanced but the timers don't tick
  assert.strictEqual(Date.now(), 12000);
});const assert = require('node:assert');
const { test } = require('node:test');

test('runAll functions following the given order', (context) => {
  context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
  const results = [];
  setTimeout(() => results.push(1), 9999);

  assert.deepStrictEqual(results, []);
  context.mock.timers.setTime(12000);
  assert.deepStrictEqual(results, []);
  // The date is advanced but the timers don't tick
  assert.strictEqual(Date.now(), 12000);
});