示例工程 07-async-promises
07-async-promises/05-abortcontroller/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
abortBeforeStart,
abortDoesNotStopWork,
abortWhileWaiting,
cancellable,
completeBeforeAbort,
defaultReason,
run,
} from './main.js';
test('启动前已取消:立即拒绝', async () => {
assert.equal(await abortBeforeStart(), 'cancelled-before');
});
test('等待中取消:清掉定时器并拒绝', async () => {
assert.equal(await abortWhileWaiting(), 'cancelled-mid');
});
test('完成后取消:结果已经确定,不受影响', async () => {
assert.equal(await completeBeforeAbort(), 'done');
});
test('默认 reason 是 AbortError', async () => {
assert.equal(await defaultReason(), 'AbortError');
});
test('取消等待不会停止底层任务', async () => {
assert.equal(await abortDoesNotStopWork(), true);
});
test('cancellable 正常完成时返回标签', async () => {
const c = new AbortController();
assert.equal(await cancellable(1, c.signal, 'ok'), 'ok');
});
test('run 输出 5 行场景与两条说明', async () => {
const out = [];
const rows = await run((s) => out.push(s));
assert.equal(rows.length, 5);
assert.equal(out.length, 8);
assert.equal(out[5], '取消等待后底层任务仍完成 => true');
assert.match(out.at(-1), /没有取消操作/);
});