Skip to content

Commit

Permalink
Merge pull request #33 from tkrotoff/undici
Browse files Browse the repository at this point in the history
Test with Undici fetch
  • Loading branch information
tkrotoff authored Dec 1, 2022
2 parents 193b8ab + 37d4d24 commit b9288c3
Show file tree
Hide file tree
Showing 11 changed files with 288 additions and 84 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## 0.15.0 (2022/12/01)

- Breaking change: createHttpError & createJSONHttpError params are no longer optional
- Test with Undici fetch

## 0.14.2 (2022/12/01)

- Update npm packages
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,8 @@ Check [examples/web](examples/web)
- `createResponsePromise(body?:` [`BodyInit`](https://fetch.spec.whatwg.org/#bodyinit)`, init?:` [`ResponseInit`](https://fetch.spec.whatwg.org/#responseinit)`): ResponsePromiseWithBodyMethods`
- `createJSONResponsePromise(body: object, init?: ResponseInit): ResponsePromiseWithBodyMethods`

- `createHttpError(body?: BodyInit, status = 0, statusText?: string): HttpError`
- `createJSONHttpError(body: object, status = 0, statusText?: string): HttpError`
- `createHttpError(body: BodyInit, status: number, statusText?: string): HttpError`
- `createJSONHttpError(body: object, status: number, statusText?: string): HttpError`

### HttpStatus

Expand Down
14 changes: 12 additions & 2 deletions jest.setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,27 @@ switch (fetchPolyfill) {
case 'whatwg-fetch': {
const whatwgFetch = require('whatwg-fetch');
globalThis.fetch = whatwgFetch.fetch;
// Tests are very slow with whatwg-fetch (150s) vs node-fetch (2s)
jest.setTimeout(10_000);
globalThis.Request = whatwgFetch.Request;
globalThis.Response = whatwgFetch.Response;
globalThis.Headers = whatwgFetch.Headers;
break;
}
case 'node-fetch': {
const nodeFetch = require('node-fetch');
globalThis.fetch = nodeFetch.default;
globalThis.Request = nodeFetch.Request;
globalThis.Response = nodeFetch.Response;
globalThis.Headers = nodeFetch.Headers;
break;
}
case 'undici': {
const undici = require('undici');
globalThis.fetch = undici.fetch;
globalThis.Request = undici.Request;
globalThis.Response = undici.Response;
globalThis.Headers = undici.Headers;
break;
}
default: {
assert(false, `Invalid fetch polyfill: '${fetchPolyfill}'`);
}
Expand Down
58 changes: 58 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"test:node-fetch": "NODE_EXTRA_CA_CERTS=./src/createTestServer/createTestServer.cert FETCH=node-fetch jest --verbose",
"test:coverage:node-fetch": "NODE_EXTRA_CA_CERTS=./src/createTestServer/createTestServer.cert FETCH=node-fetch jest --coverage",
"test:whatwg-fetch": "NODE_EXTRA_CA_CERTS=./src/createTestServer/createTestServer.cert FETCH=whatwg-fetch jest --env=jsdom --verbose",
"test:undici": "NODE_EXTRA_CA_CERTS=./src/createTestServer/createTestServer.cert FETCH=undici jest --verbose",
"test:coverage:whatwg-fetch": "NODE_EXTRA_CA_CERTS=./src/createTestServer/createTestServer.cert FETCH=whatwg-fetch jest --env=jsdom --coverage",
"test:e2e": "playwright test",
"test:e2e:debug": "playwright test --debug",
Expand Down Expand Up @@ -89,6 +90,7 @@
"tslib": "^2.4.1",
"typescript": "^4.9.3",
"ua-parser-js": "^1.0.32",
"undici": "^5.13.0",
"whatwg-fetch": "^3.6.2"
}
}
59 changes: 42 additions & 17 deletions src/Http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import assert from 'node:assert';

import { createTestServer } from './createTestServer/createTestServer';
import { entriesToObject } from './utils/entriesToObject';
import { isWhatwgFetch } from './utils/isWhatwgFetch';
import { defaults, del, get, patch, patchJSON, post, postJSON, put, putJSON } from './Http';

const path = '/';
Expand Down Expand Up @@ -480,7 +479,7 @@ describe('body methods', () => {
const response = await get(url).blob();
expect(response.size).toEqual(3);
// FIXME https://github.com/jsdom/jsdom/issues/2555
if (!isWhatwgFetch) {
if (process.env.FETCH !== 'whatwg-fetch') {
// eslint-disable-next-line jest/no-conditional-expect
expect(await response.text()).toEqual('*/*');
}
Expand Down Expand Up @@ -598,11 +597,24 @@ describe('body methods', () => {
});

// https://github.com/whatwg/fetch/issues/1147
// eslint-disable-next-line unicorn/consistent-function-scoping
const nodeFetchBodyAlreadyUsedError = (url: string) => `body used already for: ${url}`;
const whatwgFetchBodyAlreadyUsedError = 'Already read';
const bodyAlreadyUsedError = (url: string) =>
isWhatwgFetch ? whatwgFetchBodyAlreadyUsedError : nodeFetchBodyAlreadyUsedError(url);
let bodyAlreadyUsedError = '';
switch (process.env.FETCH) {
case 'node-fetch': {
bodyAlreadyUsedError = 'body used already for: ';
break;
}
case 'whatwg-fetch': {
bodyAlreadyUsedError = 'Already read';
break;
}
case 'undici': {
bodyAlreadyUsedError = 'Body is unusable';
break;
}
default: {
assert(false, `Unknown FETCH env '${process.env.FETCH}'`);
}
}

test('multiple body calls using helpers', async () => {
const server = createTestServer();
Expand All @@ -614,7 +626,7 @@ describe('body methods', () => {

const response = get(url);
expect(await response.json()).toEqual({ accept: 'application/json' });
await expect(response.text()).rejects.toThrow(bodyAlreadyUsedError(url));
await expect(response.text()).rejects.toThrow(bodyAlreadyUsedError);

// FIXME await close() is too slow with Fastify 4.10.2
server.close();
Expand All @@ -630,7 +642,7 @@ describe('body methods', () => {

const response = await get(url);
expect(await response.json()).toEqual({ accept: '*/*' });
await expect(response.text()).rejects.toThrow(bodyAlreadyUsedError(url));
await expect(response.text()).rejects.toThrow(bodyAlreadyUsedError);

// FIXME await close() is too slow with Fastify 4.10.2
server.close();
Expand All @@ -647,7 +659,7 @@ describe('body methods', () => {
const response = get(url);
expect(await response.json()).toEqual({ accept: 'application/json' });
// eslint-disable-next-line unicorn/no-await-expression-member
await expect((await response).text()).rejects.toThrow(bodyAlreadyUsedError(url));
await expect((await response).text()).rejects.toThrow(bodyAlreadyUsedError);

// FIXME await close() is too slow with Fastify 4.10.2
server.close();
Expand All @@ -657,11 +669,24 @@ describe('body methods', () => {
test('cannot connect', async () => {
const url = 'http://localhost/';

const nodeFetchRequestFailedError = `request to ${url} failed, reason: connect ECONNREFUSED 127.0.0.1:80`;
const whatwgFetchRequestFailedError = 'Network request failed';
const requestFailedError = isWhatwgFetch
? whatwgFetchRequestFailedError
: nodeFetchRequestFailedError;
let requestFailedError = '';
switch (process.env.FETCH) {
case 'node-fetch': {
requestFailedError = `request to ${url} failed, reason: connect ECONNREFUSED 127.0.0.1:80`;
break;
}
case 'whatwg-fetch': {
requestFailedError = 'Network request failed';
break;
}
case 'undici': {
requestFailedError = 'fetch failed';
break;
}
default: {
assert(false, `Unknown FETCH env '${process.env.FETCH}'`);
}
}

// Avoid console to be polluted with whatwg-fetch "Error: connect ECONNREFUSED"
const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
Expand All @@ -671,12 +696,12 @@ test('cannot connect', async () => {
} catch (e) {
assert(e instanceof Error);
/* eslint-disable jest/no-conditional-expect */
expect(e.name).toEqual(isWhatwgFetch ? 'TypeError' : 'FetchError');
expect(e.name).toEqual(process.env.FETCH === 'node-fetch' ? 'FetchError' : 'TypeError');
expect(e.message).toEqual(requestFailedError);
/* eslint-enable jest/no-conditional-expect */
}

expect(consoleSpy).toHaveBeenCalledTimes(isWhatwgFetch ? 1 : 0);
expect(consoleSpy).toHaveBeenCalledTimes(process.env.FETCH === 'whatwg-fetch' ? 1 : 0);

consoleSpy.mockRestore();
});
Expand Down
Loading

0 comments on commit b9288c3

Please sign in to comment.