示例工程 20-network-storage-fetch
20-network-storage-fetch/01-fetch-status/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { classify, inspect, run } from './main.js';
test('classify 区分成功、客户端错误、服务端错误与重定向', () => {
assert.equal(classify({ ok: true, status: 200 }).category, 'success');
assert.equal(classify({ ok: false, status: 404 }).category, 'client-error');
assert.equal(classify({ ok: false, status: 500 }).category, 'server-error');
assert.equal(classify({ ok: true, status: 302 }).category, 'redirect');
});
test('404 的 response.ok 为 false,但 inspect 不会抛错', async () => {
const fake = async () => ({
ok: false,
status: 404,
text: async () => '{"error":"not found"}',
});
const result = await inspect('./missing', fake);
assert.equal(result.ok, false);
assert.equal(result.status, 404);
assert.equal(result.category, 'client-error');
assert.match(result.body, /not found/);
});
test('网络错误仍然会 reject', async () => {
const fake = async () => {
throw new TypeError('network down');
};
await assert.rejects(() => inspect('./x', fake), /network down/);
});
test('响应体只截取前 60 个字符', async () => {
const fake = async () => ({ ok: true, status: 200, text: async () => 'x'.repeat(200) });
const result = await inspect('./x', fake);
assert.equal(result.body.length, 60);
});
test('run 在 Node 里给出环境错误(无相对 URL fetch 上下文)', async () => {
await assert.rejects(() => run(() => {}));
});