【问题标题】:Cypress - cy.intercept catching wrong urlCypress - cy.intercept 捕获错误的 url
【发布时间】:2021-02-15 21:21:23
【问题描述】:

我尝试使用intercept 模拟我的 API 路由,但我不知道为什么触发的路由错误(我在 cypress@6.2.1)

我有两个拦截:

一个用于/contacts,第二个用于/contacts/Contact-ARandomId

cy.intercept('GET', 'http://localhost:5000/contacts', {statusCode: 200, body: dataMultiple})

cy.intercept('GET', 'http://localhost:5000/contacts/Contact-ARandomId', {statusCode: 200, body: dataARandomId})

【问题讨论】:

    标签: javascript cypress


    【解决方案1】:

    参考Matching URL

    您可以提供要匹配的 URL 的 子字符串

    // 将匹配任何包含“用户”子字符串的请求,例如
    // GET /users?_limit=3 和 POST /users

    cy.intercept('用户')

    所以'http://localhost:5000/contacts' 匹配,因为它是第一个定义的,并且适用部分匹配。

    您可以颠倒拦截的顺序,首先设置更具体的 URL(有点像 SPA 上的路由)。

    或者,看看Set an alias dynamically

    您可以使用 javascript 来优化响应

    cy.intercept('GET', 'http://localhost:5000/contacts', (req) => {
    
      const isContactById = req.url.split('/')  // split into parts
        .pop()                                  // take last part
        .startsWith('Contact-');                // check if has id prefix
    
      const bodyStub = isContactById ? dataARandomId : dataMultiple;
      req.reply(200, bodyStub);
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-03
      • 2021-03-10
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2018-01-31
      • 2017-05-04
      • 2017-01-04
      相关资源
      最近更新 更多