Skip to content

Commit

Permalink
Support relative urls
Browse files Browse the repository at this point in the history
  • Loading branch information
IanVS committed Nov 7, 2024
1 parent 3e03ca4 commit 011afe9
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 3 deletions.
19 changes: 17 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,21 @@ function requestNotMatches(request: Request, urlOrPredicate: UrlOrPredicate): bo
return !requestMatches(request, urlOrPredicate);
}

// Node 18 does not support URL.canParse()
export function canParseURL(url: string): boolean {
try {
new URL(url);
return true;
} catch (err) {
return false;
}
}

// Node Requests cannot be relative
function resolveInput(input: string): string {
return typeof location !== 'undefined' && !canParseURL(input) ? new URL(input, location.origin).toString() : input;
}

function normalizeRequest(input: RequestInput, requestInit?: RequestInit): Request {
if (input instanceof Request) {
if (input.signal && input.signal.aborted) {
Expand All @@ -319,12 +334,12 @@ function normalizeRequest(input: RequestInput, requestInit?: RequestInit): Reque
if (requestInit && requestInit.signal && requestInit.signal.aborted) {
abort();
}
return new Request(input, requestInit);
return new Request(resolveInput(input), requestInit);
} else {
if (requestInit && requestInit.signal && requestInit.signal.aborted) {
abort();
}
return new Request(input.toString(), requestInit);
return new Request(resolveInput(input.toString()), requestInit);
}
}

Expand Down
8 changes: 8 additions & 0 deletions tests/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,14 @@ describe('testing mockResponse', () => {
expect(fetch.mock.calls[0]![0]).toEqual(new URL('https://instagram.com'));
});

it('should support relative request urls', async () => {
fetch.mockResponseOnce(JSON.stringify({ data: 'abcde' }), { status: 200 });

const response = await fetch('folder/file.json').then((res) => res.json());

expect(response).toEqual({ data: 'abcde' });
});

it('should allow empty response bodies', async () => {
fetch.mockResponseOnce(null, { status: 204 });
fetch.mockResponseOnce(undefined, { status: 204 });
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": [
"es2022"
"es2022",
"dom",
],
"baseUrl": "./",
"paths": {
Expand Down
3 changes: 3 additions & 0 deletions vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,7 @@ export default defineConfig({
'vitest-fetch-mock': './src/index',
},
},
test: {
environment: 'jsdom',
},
});

0 comments on commit 011afe9

Please sign in to comment.