Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Last active March 7, 2024 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ziadoz/a3b1f41721303155487140170d62e3ed to your computer and use it in GitHub Desktop.
Save ziadoz/a3b1f41721303155487140170d62e3ed to your computer and use it in GitHub Desktop.
Plain JS - Fake JSON Response From fetch()
// Create a proxy to fetch which returns a pre-determined fake JSON response
window.fetch = new Proxy(window.fetch, {
apply(target, that, args) {
return Promise.resolve(
new Response(
'{ "foo": "bar" }',
{ status: 200, headers: { 'Content-Type': 'application/json' }},
)
);
},
});
// Call fetch() and log the fake response
fetch('https://www.example.com')
.then((r) => r.json())
.then((j) => console.log(j.foo))
.catch((e) => console.log('error', e.message));
// This is useful for Laravel Dusk or Codeception browser tests, when you don't want to hit a real API route.
<?php
namespace Tests;
use Laravel\Dusk\Browser;
trait FakesJavaScriptFetch
{
// Usage: $browser->script($this->fakeFetchResponse(['foo' => 'bar']));
public function fakeFetchResponse(array $data): string
{
$json = json_encode($data);
return <<<SCRIPT
window.fetch = new Proxy(window.fetch, {
apply(target, that, args) {
return Promise.resolve(
new Response(
'$json',
{ status: 200, headers: { 'Content-Type': 'application/json' }},
)
);
},
});
SCRIPT;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment