|
| 1 | +import { makeHttpRequest } from '../http-request'; |
| 2 | +import { SolanaHttpError } from '../http-request-errors'; |
| 3 | + |
| 4 | +describe('makeHttpRequest', () => { |
| 5 | + describe('when the endpoint returns a non-200 status code', () => { |
| 6 | + beforeEach(() => { |
| 7 | + fetchMock.once('', { status: 404, statusText: 'We looked everywhere' }); |
| 8 | + }); |
| 9 | + it('throws HTTP errors', async () => { |
| 10 | + expect.assertions(3); |
| 11 | + const requestPromise = makeHttpRequest({ payload: 123, url: 'fake://url' }); |
| 12 | + await expect(requestPromise).rejects.toThrow(SolanaHttpError); |
| 13 | + await expect(requestPromise).rejects.toThrow(/We looked everywhere/); |
| 14 | + await expect(requestPromise).rejects.toMatchObject({ statusCode: 404 }); |
| 15 | + }); |
| 16 | + }); |
| 17 | + describe('when the transport fatals', () => { |
| 18 | + beforeEach(() => { |
| 19 | + fetchMock.mockReject(new TypeError('Failed to fetch')); |
| 20 | + }); |
| 21 | + it('passes the exception through', async () => { |
| 22 | + expect.assertions(1); |
| 23 | + await expect(makeHttpRequest({ payload: 123, url: 'fake://url' })).rejects.toThrow( |
| 24 | + new TypeError('Failed to fetch') |
| 25 | + ); |
| 26 | + }); |
| 27 | + }); |
| 28 | + describe('when the endpoint returns a well-formed JSON response', () => { |
| 29 | + beforeEach(() => { |
| 30 | + fetchMock.once(JSON.stringify({ ok: true })); |
| 31 | + }); |
| 32 | + it('calls fetch with the specified URL', () => { |
| 33 | + makeHttpRequest({ payload: 123, url: 'fake://url' }); |
| 34 | + expect(fetchMock).toHaveBeenCalledWith('fake://url', expect.anything()); |
| 35 | + }); |
| 36 | + it('sets the `body` to a stringfied version of the payload', () => { |
| 37 | + makeHttpRequest({ payload: { ok: true }, url: 'fake://url' }); |
| 38 | + expect(fetchMock).toHaveBeenCalledWith( |
| 39 | + expect.anything(), |
| 40 | + expect.objectContaining({ |
| 41 | + body: JSON.stringify({ ok: true }), |
| 42 | + }) |
| 43 | + ); |
| 44 | + }); |
| 45 | + it('sets the content type header to `application/json`', () => { |
| 46 | + makeHttpRequest({ payload: 123, url: 'fake://url' }); |
| 47 | + expect(fetchMock).toHaveBeenCalledWith( |
| 48 | + expect.anything(), |
| 49 | + expect.objectContaining({ |
| 50 | + headers: expect.objectContaining({ |
| 51 | + 'Content-type': 'application/json', |
| 52 | + }), |
| 53 | + }) |
| 54 | + ); |
| 55 | + }); |
| 56 | + it('sets the `method` to `POST`', () => { |
| 57 | + makeHttpRequest({ payload: 123, url: 'fake://url' }); |
| 58 | + expect(fetchMock).toHaveBeenCalledWith( |
| 59 | + expect.anything(), |
| 60 | + expect.objectContaining({ |
| 61 | + method: 'POST', |
| 62 | + }) |
| 63 | + ); |
| 64 | + }); |
| 65 | + }); |
| 66 | +}); |
0 commit comments