Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/narou-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ export default class NarouNovelFetch extends NarouNovel {

const res = await (this.fetch ?? fetch)(url, options?.fetchOptions);

if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
}

if (!query.gzip) {
return (await res.json()) as T;
}
Expand Down
30 changes: 29 additions & 1 deletion test/narou-fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ describe('NarouNovelFetch', () => {
it('should use custom fetch function when provided', async () => {
// カスタムフェッチ関数をモック
const customFetchMock = vi.fn().mockResolvedValue({
ok: true,
json: vi.fn().mockResolvedValue(mockData)
});

Expand All @@ -95,6 +96,33 @@ describe('NarouNovelFetch', () => {
expect(result).toEqual(mockData);
});

it.each([403, 404, 429, 500])('should reject HTTP %i before reading the body', async (status) => {
for (const gzip of [0, 5] as const) {
const response = Response.json(mockData, { status });
const jsonSpy = vi.spyOn(response, 'json');
const bufferSpy = vi.spyOn(response, 'arrayBuffer');
const narouFetch = new NarouNovelFetch(vi.fn().mockResolvedValue(response));

await expect(narouFetch.executeRanking({ rtype: '20260101-d', gzip }))
.rejects.toThrow(`HTTP ${status}:`);
expect(jsonSpy).not.toHaveBeenCalled();
expect(bufferSpy).not.toHaveBeenCalled();
expect(response.bodyUsed).toBe(false);
}
});

it.each([0, 5] as const)('should still reject plain API errors returned with HTTP 200 (gzip=%i)', async (gzip) => {
const response = new Response('Error: Invalid date.', { status: 200 });
const narouFetch = new NarouNovelFetch(vi.fn().mockResolvedValue(response));
const result = narouFetch.executeRanking({ rtype: '20260101-d', gzip });

if (gzip === 0) {
await expect(result).rejects.toBeInstanceOf(SyntaxError);
} else {
await expect(result).rejects.toBe('Error: Invalid date.');
}
});

it('should set gzip to 5 when undefined', async () => {
// URLパラメータをキャプチャするモック
const requestSpy = vi.fn();
Expand Down Expand Up @@ -185,4 +213,4 @@ describe('NarouNovelFetch', () => {
{ fetchOptions: { headers: { 'user-agent': 'node-narou' } } }
);
});
});
});
Loading