使用明确的函数
\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); });