import { test } from 'node:test'; import assert from 'node:assert/strict'; import { awaitIsMicrotask, collectOrder, timeoutVsImmediate } from './main.js'; test('完整顺序:同步 → 微任务 → 宏任务', async () => { const order = await collectOrder(); assert.deepEqual(order, [ '1 sync-start', '5 async-start', '10 sync-end', '3 queueMicrotask', '4 promise-then', '6 after-await', '7 then-a', '8 nested-microtask', '9 then-b', '2 timeout', ]); }); test('await 之后的代码是微任务:调用方先继续,随后才恢复', async () => { let resumed = false; const p = awaitIsMicrotask().then(() => { resumed = true; }); assert.equal(resumed, false, 'await 让出后,调用方先执行'); await p; assert.equal(resumed, true); }); test('微任务先于任何宏任务', async () => { const out = []; setTimeout(() => out.push('timeout'), 0); queueMicrotask(() => out.push('microtask')); out.push('sync'); await new Promise((r) => setTimeout(r, 5)); assert.deepEqual(out, ['sync', 'microtask', 'timeout']); }); test('嵌套微任务在下一个 then 之前执行', async () => { const out = []; await new Promise((resolve) => { Promise.resolve() .then(() => { out.push('a'); queueMicrotask(() => out.push('b')); }) .then(() => { out.push('c'); resolve(); }); }); assert.deepEqual(out, ['a', 'b', 'c']); }); test('setImmediate 与 setTimeout 都属于宏任务,顺序由任务源决定', async () => { const out = await timeoutVsImmediate(); assert.equal(out[0], 'sync'); assert.equal(out[1], 'microtask'); assert.ok(out.includes('timeout')); assert.ok(out.includes('immediate')); });