【问题标题】:How do I can catch and modify XHR JSON response in cypress?如何在 cypress 中捕获和修改 XHR JSON 响应?
【发布时间】:2021-02-19 22:29:43
【问题描述】:

在 Cypress 中可以存根 XHR 响应,但我想捕获和修改 JSON 响应。

https://docs.cypress.io/guides/guides/network-requests.html#Stub-Responses https://docs.cypress.io/api/commands/route.html#With-Stubbing

我没有找到一个很好的例子来解释这一点。

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

/isHuman

响应是:

{"isHuman":true}

我想拦截这个调用并把 true 和另一个测试用 false

谁能提供这个?

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

我需要更改该 xhr 调用的响应。

【问题讨论】:

    标签: json xmlhttprequest cypress


    【解决方案1】:

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

    it('should od whatever', () => {
      cy.route('GET', '/isHuman', { "isHuman": true });
      /* trigger some requests */
    
      cy.route('GET', '/isHuman', { "isHuman": false });
      /* trigger other requests */
    });
    

    【讨论】:

    • 我不必使用 cy.server() 吗?我不知道何时调用此 XHR。我可以将 cy.route() 放在任何地方吗?
    • 你必须使用cy.server(),但它通常放在beforeEach()
    • 嗨,类似的问题,但我想部分模拟 XHR 响应。例如,在上面的示例中,json oblect 中有许多属性,不编辑它们我只想编辑 isHuman 属性。有什么方法可以实现@martin
    【解决方案2】:
     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')
        })
    

    下面是代码的来源:

    Partial route mock

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-19
      • 2019-04-26
      • 2021-05-22
      • 1970-01-01
      • 2017-07-19
      • 2014-09-16
      • 2014-08-24
      • 2017-04-22
      相关资源
      最近更新 更多