如何在cypress中捕获和修改XHR JSON响应



在Cypress中有可能截断XHR响应,但我想捕获并修改JSON响应。

https://docs.cypress.io/guides/guides/network-requests.html#Stub-回应https://docs.cypress.io/api/commands/route.html#With-存根

我找不到一个好的例子来解释这一点。

在我的应用程序中有一个对API的调用:

/isHuman

响应为:

{"isHuman":true}

我想拦截这个呼叫,并将true设置为,并用false设置另一个测试

有人能提供这个吗?

上次编辑:在localhost上测试应用程序(我在其中定义baseURL-localhost:3123(,但有对不同域的api调用(https://api.app.com/isHuman(。

我需要更改xhr呼叫的响应。

您可以在同一it():内多次重新定义同一url

it('should od whatever', () => {
cy.route('GET', '/isHuman', { "isHuman": true });
/* trigger some requests */
cy.route('GET', '/isHuman', { "isHuman": false });
/* trigger other requests */
});
it('modifies the response from the server to insert Kiwi', () => {
cy.intercept('favorite-fruits', (req) => {
req.reply((res) => {
// add Kiwi to the list received from the server
console.log('original response from the server is %s %o', typeof res.body, res.body)
const list = res.body
list.push('Kiwi')
res.send(list)
})
})
cy.visit('/')
// check if Kiwi is the last fruit
cy.get('li').should('have.length.gt', 3)
.last().should('contain', 'Kiwi')
})

以下是代码的来源:

部分路线模拟

最新更新