木偶拦截请求并在json中响应 [英] Puppeteer intercept request and respond in json

查看:90
本文介绍了木偶拦截请求并在json中响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,木偶提供了一个非常基本的示例,即拦截对图片的url的请求,并使用不同的url响应不同的图片.来自他们的文档的示例在这里: https://github.com/webdriverio/webdriverio/tree/master/packages/devtools

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

我的问题是我正在尝试拦截XHR请求并使用自己的json进行响应.我似乎找不到关于此的文档.如果有人可以分享有关此内容的更多文档,那就太好了.或提供示例.

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.

我希望能够基于GET或POST请求之类的http方法进行拦截.并基于URL路径.能够使用通配符以及/api/v1/foo/:id 它将识别出:id 是通配符,并且可以在那里接受任何内容.

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.

然后可以使用状态200和自定义的json响应进行响应.最终,我正在寻找它.

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()
    })

推荐答案

您可以使用 Mockiavelli -请求Puppeteer的模拟库.它可以基于方法和路径来响应请求,并具有对路径参数(:param )的内置支持.它与jest和jest-puppeteer集成得最好,但可与任何测试库一起使用.

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.

这篇关于木偶拦截请求并在json中响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆