Files
RSSHub/lib/utils/ofetch.test.ts
Tony 6697901e29 style: use cloudflare/oxlint-config (#23968)
* style: use cloudflare/oxlint-config

* style: fix no-known-value-widening

* style: fix typescript/only-throw-error

* style: fix typescript/no-floating-promises

* style: fix typescript/use-unknown-in-catch-callback-variable

* style: fix typescript/no-misused-promises

* style: fix typescript/no-unsafe-unary-minus

* style: fix typescript/no-for-in-array

* style: fix react/purity

* style: fix typescript/switch-exhaustiveness-check

* style: fix typescript/unbound-method

* style: fix react/rules-of-hooks

* style: fix typescript/return-await

* style: fix react/button-has-type

* style: fix react/no-unescaped-entities

* style: fix import/no-namespace

* style: fix typescript/no-import-type-side-effects

* style: fix no-promise-executor-return

* style: fix no-useless-assignment

* style: fix typescript/no-misused-spread

* style: fix react/jsx-no-target-blank

* style: fix typescript/await-thenable

* style: fix typescript/no-unnecessary-type-assertion

* style: fix import/consistent-type-specifier-style

* style: fix react/no-unknown-property

* style: remove unused disable directive

* style: merge region

* style: enable prefer-smaller-scope

* style: add react/no-danger

* style: add unicorn-js/prefer-uint8array-base64/hex

* style: move non-recommended unicorn rules to custom region
2026-11-21 03:38:53 +08:00

130 lines
5.2 KiB
TypeScript

import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { http as mswHttp, HttpResponse } from 'msw';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { z } from 'zod';
const isAddressInfo = (address: string | AddressInfo | null): address is AddressInfo => typeof address === 'object' && address !== null;
const loadOfetchWithLogger = async () => {
vi.resetModules();
const { default: logger } = await import('@/utils/logger');
const { default: ofetch } = await import('@/utils/ofetch');
return { logger, ofetch };
};
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
describe('ofetch', () => {
it('marks prefer-proxy header on retryable responses', async () => {
const { default: server } = await import('@/setup.test');
server.use(mswHttp.get('http://rsshub.test/fail-500', () => HttpResponse.text('fail', { status: 500 })));
const { logger, ofetch } = await loadOfetchWithLogger();
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger);
await expect(
ofetch('http://rsshub.test/fail-500', {
retry: 1,
retryDelay: 0,
onResponse({ options }) {
(options as { headers: Headers | null }).headers = null;
},
})
).rejects.toBeDefined();
expect(warnSpy).toHaveBeenCalled();
});
it('surfaces the root cause in fetch error messages', async () => {
const { logger, ofetch } = await loadOfetchWithLogger();
vi.spyOn(logger, 'error').mockImplementation(() => logger);
const networkError = new TypeError('fetch failed', { cause: new Error('getaddrinfo ENOTFOUND t.me') });
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(networkError));
await expect(ofetch('https://t.me/s/telegram', { retry: 0 })).rejects.toThrow('fetch failed (getaddrinfo ENOTFOUND t.me)');
});
it('logs redirected responses', async () => {
const { logger, ofetch } = await loadOfetchWithLogger();
const httpSpy = vi.spyOn(logger, 'http').mockImplementation(() => logger);
const server = http.createServer((req, res) => {
if (req.url === '/redirect') {
res.statusCode = 302;
res.setHeader('Location', '/target');
res.end();
return;
}
res.statusCode = 200;
res.end('ok');
});
await new Promise<void>((resolve) => {
server.listen(0, resolve);
});
const address = server.address();
if (!isAddressInfo(address)) {
throw new TypeError('expected the test server to listen on a TCP port');
}
const { port } = address;
try {
await ofetch(`http://127.0.0.1:${port}/redirect`);
} finally {
server.close();
}
expect(httpSpy).toHaveBeenCalled();
});
it('parses response data with the supplied schema', async () => {
const { default: server } = await import('@/setup.test');
server.use(mswHttp.get('http://rsshub.test/schema-valid', () => HttpResponse.json({ code: 0, data: { list: ['a'], extra: true } })));
const { ofetch } = await loadOfetchWithLogger();
const listSchema = z.array(z.string()).transform((list) => list.map((item) => item.toUpperCase()));
const schema = z.object({ code: z.literal(0), data: z.object({ list: listSchema }) });
// The parsed output is returned: unknown keys are stripped and transforms are applied.
const response = await ofetch('http://rsshub.test/schema-valid', { schema });
expect(response).toEqual({ code: 0, data: { list: ['A'] } });
const rawResponse = await ofetch.raw('http://rsshub.test/schema-valid', { schema });
expect(rawResponse._data).toEqual({ code: 0, data: { list: ['A'] } });
});
it('rejects response data that does not match the schema', async () => {
const { default: server } = await import('@/setup.test');
server.use(mswHttp.get('http://rsshub.test/schema-invalid', () => HttpResponse.json({ code: 1 })));
const { ofetch } = await loadOfetchWithLogger();
const schema = z.object({ code: z.literal(0) });
await expect(ofetch('http://rsshub.test/schema-invalid', { schema })).rejects.toBeInstanceOf(z.ZodError);
});
it('skips schema validation on error responses', async () => {
const { default: server } = await import('@/setup.test');
server.use(mswHttp.get('http://rsshub.test/schema-error', () => HttpResponse.text('boom', { status: 500 })));
const { logger, ofetch } = await loadOfetchWithLogger();
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger);
const schema = z.object({ code: z.literal(0) });
// The request fails with the HTTP error, not with a schema error.
await expect(
ofetch('http://rsshub.test/schema-error', {
schema,
retry: 1,
retryDelay: 0,
})
).rejects.toMatchObject({ name: 'FetchError', statusCode: 500 });
expect(warnSpy).toHaveBeenCalled();
});
});