UNPKG

@exodus/networking-spec

Version:

Platform-agnostic test suites for networking related features

73 lines (72 loc) 3.02 kB
import timers from './timers'; export function testsuite(getInstance, mockAdapter) { describe('HttpClient', () => { let httpClient; beforeEach(() => { httpClient = getInstance(); timers.useFakeTimers(); }); afterEach(() => { timers.useRealTimers(); }); function fail(msg) { expect(false).toEqual(msg); } describe('fetch', () => { const url = 'https://wayne-foundation.com'; const requestBody = { city: 'Gotham City', location: 'Wayne Tower' }; const requests = [ { description: 'simple request', init: { method: 'GET', headers: { Authorization: 'Bearer my-token', }, }, }, { description: 'request with body', init: { method: 'POST', body: JSON.stringify(requestBody), headers: { Authorization: 'Bearer my-token' }, }, }, ]; requests.forEach(({ init, description }) => { it(`should resolve a ${description} (${init.method}) to ${url}`, async () => { const expectedResponse = { name: 'James Gordon' }; mockAdapter.replyWith(200, expectedResponse); const response = await httpClient.fetch(url, init); const requests = mockAdapter.requests(); expect(requests.length).toEqual(1); const { body, headers, ...initWithoutBodyAndHeaders } = init; const { url: actualUrl, headers: actualHeaders, ...actualRequest } = requests[0]; expect(actualUrl).toMatch(new RegExp(`${url}/?$`, 'u')); expect(actualHeaders).toEqual(expect.objectContaining(headers)); expect(actualRequest).toEqual(initWithoutBodyAndHeaders); expect(await response.json()).toEqual(expectedResponse); }); }); describe('timeout', () => { const timeout = 100; it('should timeout after specified duration', (done) => { httpClient .fetch(url, { timeoutMs: timeout, }) .then(() => { fail('request should have timed out'); return done(); }) .catch((e) => { expect(e.message.toLowerCase()).toContain('timeout'); done(); }); timers.advanceTimersByTime(timeout + 5); }, timeout + 5); }); }); }); }