如何模拟不同来源url的相同请求(对于TestCafe)



我需要模拟由2个不同来源(url1, url2)发起的相同请求。但是只有一个请求(来自第一个源url1)被模拟。如何处理多个起源?提前谢谢。

const urlRegExp = new RegExp('/events');
const mock = RequestMock()
    .onRequestTo(urlRegExp)
    .respond({eenter code hererror: 'this request has been mocked'}, 500, {
        'access-control-allow-origin': 'url1.com',
        'access-control-allow-credentials': true
    })
    .onRequestTo(urlRegExp)
    .respond({error: 'this request has been mocked'}, 500, {
        'access-control-allow-origin': 'url2.com',
        'access-control-allow-credentials': true
    });

您需要修改您的onRequestTo调用。请查看TestCafe文档中的Filter With Predicate部分。

const mock = RequestMock()
    .onRequestTo(request => {
        return request.url === 'http://example.com' &&
               request.method === 'post' &&
               request.isAjax &&
               request.body.toString() === 'foo=bar';
    })
    .respond(/*...*/);

你可以设置你的请求模拟来过滤请求的请求头,如主机,referer, origin等。因此,您需要为不同的请求编写不同的过滤器。

最新更新