使用明确的函数
🌐 Using clear functions
如前所述,所有来自定时器的清除函数(clearTimeout、clearInterval 和 clearImmediate)都会被隐式模拟。来看这个使用 setTimeout 的示例:
🌐 As mentioned, all clear functions from timers (clearTimeout, clearInterval,and
clearImmediate) are implicitly mocked. Take a look at this example using setTimeout:
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(); // Optionally choose what to mock context.mock.timers.enable({ apis: ['setTimeout'] }); const id = setTimeout(fn, 9999); // Implicitly mocked as well clearTimeout(id); context.mock.timers.tick(9999); // As that setTimeout was cleared the mock function will never be called assert.strictEqual(fn.mock.callCount(), 0); });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(); // Optionally choose what to mock context.mock.timers.enable({ apis: ['setTimeout'] }); const id = setTimeout(fn, 9999); // Implicitly mocked as well clearTimeout(id); context.mock.timers.tick(9999); // As that setTimeout was cleared the mock function will never be called assert.strictEqual(fn.mock.callCount(), 0); });