jcayzac
jcayzac7mo ago

How to build a Response object with the 'url' property set

Writing unit tests. Some functions parse Response objects. How do I create some where the url property isn't an empty string? Crafting statusText and headers to mimick a server response from a certain host doesn't seem to work.
3 Replies
jcayzac
jcayzac7mo ago
Never mind, this works:
const response = (url: string, headers: HeadersInit) => {
const r = new Response(null, { headers })
Object.defineProperty(r, 'url', { value: url })
return r
}
const response = (url: string, headers: HeadersInit) => {
const r = new Response(null, { headers })
Object.defineProperty(r, 'url', { value: url })
return r
}
Deno AI Helper
Deno AI Helper7mo ago
I wasn't able to find the answer to your question in the official Deno documentation. However, based on your message, I can provide some general advice. In JavaScript, the Response object is typically constructed with a body and an init dictionary that can include various properties, but the url property is not one that can be set directly during construction. The url property of a Response object is typically set by the browser or Deno runtime to the URL of the response. If you are writing unit tests and need to mock a Response object with a specific url, you might consider creating a wrapper or using a mocking library that allows you to set arbitrary properties on objects for testing purposes. Here's a simple example of how you might create a mock Response object with a url property:
function createMockResponse(body, init, url) {
let response = new Response(body, init);
response.url = url; // Manually set the url property
return response;
}

// Usage
let mockResponse = createMockResponse('body', { status: 200, statusText: 'OK' }, 'https://example.com');
function createMockResponse(body, init, url) {
let response = new Response(body, init);
response.url = url; // Manually set the url property
return response;
}

// Usage
let mockResponse = createMockResponse('body', { status: 200, statusText: 'OK' }, 'https://example.com');
Please note that this advice is not based on the Deno documentation, and you should double-check the accuracy of this advice. It's also important to remember that modifying built-in objects like this can lead to unexpected behavior in a real-world application, but it might be acceptable in the context of unit tests where you control the environment.
jcayzac
jcayzac7mo ago
No bot, you cannot set a readonly property 🙂