| 1 |
import { getSiteProfile } from '@launch/api/DataApi'; |
| 2 |
|
| 3 |
const fallback = { |
| 4 |
aiSiteType: null, |
| 5 |
aiSiteCategory: null, |
| 6 |
aiDescription: null, |
| 7 |
aiKeywords: [], |
| 8 |
logoObjectName: null, |
| 9 |
}; |
| 10 |
|
| 11 |
const originalFetch = global.fetch; |
| 12 |
|
| 13 |
describe('getSiteProfile', () => { |
| 14 |
beforeEach(() => { |
| 15 |
global.fetch = jest.fn(); |
| 16 |
}); |
| 17 |
|
| 18 |
afterEach(() => { |
| 19 |
jest.clearAllMocks(); |
| 20 |
global.fetch = originalFetch; |
| 21 |
}); |
| 22 |
|
| 23 |
it('returns parsed JSON when fetch succeeds', async () => { |
| 24 |
const mockResponse = { |
| 25 |
aiSiteType: 'portfolio', |
| 26 |
aiSiteCategory: 'creative', |
| 27 |
aiDescription: 'test', |
| 28 |
aiKeywords: ['design'], |
| 29 |
logoObjectName: 'logo.png', |
| 30 |
}; |
| 31 |
global.fetch.mockResolvedValueOnce({ |
| 32 |
ok: true, |
| 33 |
json: () => mockResponse, |
| 34 |
}); |
| 35 |
|
| 36 |
const result = await getSiteProfile({ |
| 37 |
title: 'My Site', |
| 38 |
description: 'Desc', |
| 39 |
}); |
| 40 |
expect(result).toEqual(mockResponse); |
| 41 |
expect(global.fetch).toHaveBeenCalledTimes(1); |
| 42 |
}); |
| 43 |
|
| 44 |
it('returns fallback when first fetch fails and second fetch throws', async () => { |
| 45 |
global.fetch |
| 46 |
.mockRejectedValueOnce(new Error('Network error')) |
| 47 |
.mockRejectedValueOnce(new Error('Still failing')); |
| 48 |
|
| 49 |
const result = await getSiteProfile({ |
| 50 |
title: 'My Site', |
| 51 |
description: 'Desc', |
| 52 |
}); |
| 53 |
expect(result).toEqual(fallback); |
| 54 |
expect(global.fetch).toHaveBeenCalledTimes(2); |
| 55 |
}); |
| 56 |
|
| 57 |
it('returns fallback when both fetches succeed but response not ok', async () => { |
| 58 |
global.fetch |
| 59 |
.mockRejectedValueOnce(new Error('Network error')) |
| 60 |
.mockResolvedValueOnce({ ok: false }); |
| 61 |
|
| 62 |
const result = await getSiteProfile({ |
| 63 |
title: 'My Site', |
| 64 |
description: 'Desc', |
| 65 |
}); |
| 66 |
expect(result).toEqual(fallback); |
| 67 |
expect(global.fetch).toHaveBeenCalledTimes(2); |
| 68 |
}); |
| 69 |
|
| 70 |
it('returns fallback when JSON parse fails', async () => { |
| 71 |
global.fetch.mockResolvedValueOnce({ |
| 72 |
ok: true, |
| 73 |
json: () => { |
| 74 |
throw new Error('Invalid JSON'); |
| 75 |
}, |
| 76 |
}); |
| 77 |
|
| 78 |
const result = await getSiteProfile({ |
| 79 |
title: 'My Site', |
| 80 |
description: 'Desc', |
| 81 |
}); |
| 82 |
expect(result).toEqual(fallback); |
| 83 |
expect(global.fetch).toHaveBeenCalledTimes(1); |
| 84 |
}); |
| 85 |
|
| 86 |
it('returns fallback when fetch resolves with undefined', async () => { |
| 87 |
global.fetch.mockResolvedValueOnce(undefined); |
| 88 |
const result = await getSiteProfile({ |
| 89 |
title: 'My Site', |
| 90 |
description: 'Desc', |
| 91 |
}); |
| 92 |
expect(result).toEqual(fallback); |
| 93 |
}); |
| 94 |
}); |
| 95 |
|