Skip to content

Commit 0b5a6ca

Browse files
fix: prevent error when stories.json has an invalid format (#794)
fixes #785
1 parent a08311a commit 0b5a6ca

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

packages/visual-service/src/storybook/utils.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,8 +112,12 @@ export async function getStoriesJson(url: string): Promise<Stories> {
112112

113113
for (const response of [storiesRes, indexRes]) {
114114
if (response.ok) {
115-
const data = await response.json() as StoriesRes | IndexRes
116-
return (data as StoriesRes).stories || (data as IndexRes).entries
115+
try {
116+
const data = await response.json() as StoriesRes | IndexRes
117+
return (data as StoriesRes).stories || (data as IndexRes).entries
118+
} catch (_ign) {
119+
// Ignore the json parse error
120+
}
117121
}
118122
}
119123
} catch (_ign) {

packages/visual-service/tests/storybook/utils.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,16 @@ describe('Storybook utils', () => {
216216
expect(data).toEqual(['entry1', 'entry2'])
217217
})
218218

219+
it('successfully fetches index entries when stories fetch has an invalid json format', async () => {
220+
// @ts-ignore
221+
vi.mocked(fetch).mockResolvedValueOnce(new Response(JSON.stringify({ entries: ['entry1', 'entry2'] }), { status: 200 }))
222+
// @ts-ignore
223+
vi.mocked(fetch).mockResolvedValueOnce(new Response('invalid json', { status: 200 }))
224+
225+
const data = await getStoriesJson('http://example.com')
226+
expect(data).toEqual(['entry1', 'entry2'])
227+
})
228+
219229
it('throws an error when both fetches fail', async () => {
220230
// @ts-ignore
221231
vi.mocked(fetch).mockResolvedValueOnce(new Response(null, { status: 404 }))

0 commit comments

Comments
 (0)