Puppeteer intercept request and respond in json

偶尔善良 提交于 2020-12-13 17:46:51

问题


So puppeteer provide pretty basic example of intercepting a request for a url to a pic, and responding with a different url to a different pic. Example from their doc here: https://github.com/webdriverio/webdriverio/tree/master/packages/devtools

My question is I'm trying to intercept an XHR request and respond with my own json. I can't seem to find the documentation on this. It would be nice if someone can share where more documentation on this can be. Or provide examples of this.

I want to be able to intercept based on the http method like GET, or POST requests. And based on the URL path. It would be nice to be able to use a wildcards as well like /api/v1/foo/:id and it would recognize :id was a wildcard and can accept anything there.

And then be able to respond with status of 200 and a customized json response. Ultimately, I'm looking for that.

Something like this is my guess:

page.on('request', interceptedRequest => {
        if (interceptedRequest.url({method: POST, body: {<some json object>} } ).endsWith('/api/v1/foo/12345')) {
            return interceptedRequest.continue({
                status: 200,
                body: {some json object }
            })
        }

        interceptedRequest.continue()
    })

回答1:


You can use Mockiavelli - request mocking library for Puppeteer. It can respond to request based on methods and path, with built-in support for path parameters (:param). It integrates best with jest and jest-puppeteer, but works with any testing library.



来源:https://stackoverflow.com/questions/60370568/puppeteer-intercept-request-and-respond-in-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!