I am trying to push fake data to test some code I have written that interacts with a third party, the reason it needs to be injected in this way is because the code doesn't exist in my test environment, so while I am receiving the correct data from the third party server, my test environment doesn't know what to do with it. So far I have created this;
const {fetch: origFetch} = window;
window.fetch = async (...args) => {
console.log("fetch called with args:", args);
const response = await origFetch(...args);
response
.clone()
.json()
.then(body => console.log("intercepted response:", body))
.catch(err => console.error(err));
/* the original response can be resolved unmodified: */
//return response;
/* or mock the response: */
return {
ok: true,
status: 200,
json: async () => ({
'element': [
'baseURI', 'https://#',
'className', 'third-party-code',
'dataSet', [
'displayMode', 'CAROUSEL',
'hideInMobile', 'true',
'navigationMethod', 'thirdParty',
],
],
'productIds': [
'1234567', 'https://#',
'ABCDEFG', 'https://#',
'8901112', 'https://#',
'HIJKLMN', 'https://#',
],
})
};
};
Now while this kind of does what I want, it's not working as expected.
Firstly, it's intercepting the first AJAX JSON response it comes across, not the one I want, secondly, I'm still not sure it's going to work.
I really need someone to show me how I can create a SHIM that will a) use the JSON response if it is valid, and b) use the fake data when not on a production level environment, or the JSON response isn't valid.
Mainly I need help creating the SHIM so I can at least test this properly, but I'd also like to target a specific JSON response.
As always any help would be greatly appreciated.