Reputation: 311
I am debugging the frontend issue which only happened in production. I am wondering if there is any way that I can mock the response of request or mock some static file.
For example,
When I call xxx.com, it loads index.html
and index.html
loads a.js
.
Since chrome cache the js, is it possible that we can mock the a.js
so that index.html
will load the mocked a.js
?
Upvotes: 21
Views: 44138
Reputation: 17438
Based on the snapshot, here's a step-by-step guide to mock or inspect API data in Chrome DevTools:
Upvotes: 0
Reputation: 35
Chrome dev tools also have a way that allows you to edit your JS file code for debugging. You can check this SO answer for list of ways.
You can also use the Redirect Rule of Requestly Chrome extension to replace the production file URL with the localhost file URL, which loads my local JS instead of production JS.
Here are the steps:
production.url/path/to/file/a.js
localhost:3000/path/to/file/a.js
localhost
JS file.In case you don’t have a local setup you can create a file mock in Requestly.
Upvotes: 1
Reputation: 563
As of Chrome 117, you can mock web content locally.
To override web content, open the Network panel, right-click a request, and select Override content.
DevTools currently supports content overrides for the following request types: images (for example, avif, png), fonts, fetch and XHR, scripts (css and js), and documents (html). DevTools now grays out the Override content option for unsupported types.
Upvotes: 14
Reputation: 5578
One more solution is npm json-server. It return stored json on each request for specified url
Upvotes: 1
Reputation: 5578
There is no way to mock a server response in devtool itself, but there are some chrome extensions helping with this: I've tried 7 of them, but ( Tweak ) the only one was able to:
Upvotes: 28
Reputation: 13792
You can try puppeteer using page.setRequestInterception()
+ request.respond()
. Something like this:
const puppeteer = require('puppeteer');
(async function main() {
try {
const browser = await puppeteer.launch({ headless: false });
const [page] = await browser.pages();
await page.setRequestInterception(true);
page.on('request', (interceptedRequest) => {
if (interceptedRequest.url() === 'https://sb.scorecardresearch.com/beacon.js') {
interceptedRequest.respond({
body: 'document.title = "42";',
});
} else {
interceptedRequest.continue();
}
});
await page.goto('https://stackoverflow.com/help');
// await browser.close();
} catch (err) {
console.error(err);
}
})();
Upvotes: 4