2022-11-17 23:30:42 +03:00
|
|
|
import { HttpClient } from '../../../src/common/services/HttpClient';
|
|
|
|
|
|
|
|
describe('HttpClient', () => {
|
2023-05-27 12:57:26 +03:00
|
|
|
const fetch = vi.fn();
|
2022-11-17 23:30:42 +03:00
|
|
|
const httpClient = new HttpClient(fetch);
|
|
|
|
|
|
|
|
describe('fetchJson', () => {
|
2022-11-20 14:54:06 +03:00
|
|
|
it('throws json on success', async () => {
|
2022-11-17 23:30:42 +03:00
|
|
|
const theError = { error: true, foo: 'bar' };
|
|
|
|
fetch.mockResolvedValue({ json: () => theError, ok: false });
|
|
|
|
|
|
|
|
await expect(httpClient.fetchJson('')).rejects.toEqual(theError);
|
|
|
|
});
|
|
|
|
|
2022-12-17 11:57:40 +03:00
|
|
|
it.each([
|
|
|
|
[undefined],
|
|
|
|
[{}],
|
|
|
|
[{ body: undefined }],
|
|
|
|
[{ body: '' }],
|
|
|
|
])('return json on failure', async (options) => {
|
2022-11-17 23:30:42 +03:00
|
|
|
const theJson = { foo: 'bar' };
|
|
|
|
fetch.mockResolvedValue({ json: () => theJson, ok: true });
|
|
|
|
|
2022-12-17 11:57:40 +03:00
|
|
|
const result = await httpClient.fetchJson('the_url', options);
|
2022-11-17 23:30:42 +03:00
|
|
|
|
|
|
|
expect(result).toEqual(theJson);
|
2022-12-17 11:57:40 +03:00
|
|
|
expect(fetch).toHaveBeenCalledWith('the_url', options);
|
|
|
|
});
|
|
|
|
|
|
|
|
it.each([
|
|
|
|
[{ body: 'the_body' }],
|
|
|
|
[{
|
|
|
|
body: 'the_body',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'text/plain',
|
|
|
|
},
|
|
|
|
}],
|
|
|
|
])('forwards JSON content-type when appropriate', async (options) => {
|
|
|
|
const theJson = { foo: 'bar' };
|
|
|
|
fetch.mockResolvedValue({ json: () => theJson, ok: true });
|
|
|
|
|
|
|
|
const result = await httpClient.fetchJson('the_url', options);
|
|
|
|
|
|
|
|
expect(result).toEqual(theJson);
|
|
|
|
expect(fetch).toHaveBeenCalledWith('the_url', expect.objectContaining({
|
|
|
|
headers: { 'Content-Type': 'application/json' },
|
|
|
|
}));
|
2022-11-17 23:30:42 +03:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2022-11-20 14:54:06 +03:00
|
|
|
describe('fetchEmpty', () => {
|
|
|
|
it('returns empty on success', async () => {
|
|
|
|
fetch.mockResolvedValue({ ok: true });
|
|
|
|
|
|
|
|
const result = await httpClient.fetchEmpty('');
|
|
|
|
|
|
|
|
expect(result).not.toBeDefined();
|
|
|
|
});
|
|
|
|
|
|
|
|
it('throws error on failure', async () => {
|
|
|
|
const theError = { error: true, foo: 'bar' };
|
|
|
|
fetch.mockResolvedValue({ json: () => theError, ok: false });
|
|
|
|
|
2023-08-08 00:06:29 +03:00
|
|
|
await expect(httpClient.fetchEmpty('')).rejects.toEqual(theError);
|
2022-11-20 14:54:06 +03:00
|
|
|
});
|
|
|
|
});
|
2022-11-17 23:30:42 +03:00
|
|
|
});
|