Last active
March 7, 2024 11:05
-
-
Save ziadoz/a3b1f41721303155487140170d62e3ed to your computer and use it in GitHub Desktop.
Plain JS - Fake JSON Response From fetch()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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