Search code examples
javascriptfetch

How do you Set the "url" when creating a new Response()?


I'm following this example to create a mocked response for a test.

Slightly modified, it looks like this:

 var data = { foo: 'bar'};
 var blob = new Blob([JSON.stringify(data)], {type : 'application/json'});
 var init = { "status" : 200 , "statusText" : "SuperSmashingGreat!" };
 var resp = new Response(blob,init);

console.log(resp.url)

body: (...)
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "SuperSmashingGreat!"
type: "default"
url: ""

this does a good job mocking the data and status however, I also want to mock resp.url I don't see how I can set that using the constructor and [since it's readonly] I can't set it on resp itself

resp.url 
>> ""
resp.url = 'www.test.com'
>> "www.test.com"
resp.url
>> ""

So how do I set the url?


Solution

  • Since url is actually defined by an inherited getter, you can use Object.definedProperty to define a simple value property directly on your Response instance, which shadows the inherited getter property:

    Object.defineProperty(resp, "url", { value: "foobar" });
    

    For your own understanding, you can see the inherited getter by looking at the property descriptor of Response.prototype.url:

    Object.getOwnPropertyDescriptor(Object.getPrototypeOf(new Response()), 'url')
    > {get: ƒ, set: undefined, enumerable: true, configurable: true}