【问题标题】:Cypress MOCK api response for different status针对不同状态的赛普拉斯 MOCK api 响应
【发布时间】:2020-08-19 08:35:02
【问题描述】:

我正在使用 Cypress 测试我的登录组件(刚开始使用它),我想处理 API 返回状态 200、400 或 500 的三种不同情况。我想模拟这些响应以查看前端如何响应.

在向我的 API 端点 http://localhost:9999/api/login 发送请求时,我想模拟三种不同情况(200、400 和 500)的响应

我已经根据文档编写了一些代码,但我仍然不是我想要的。

describe('Login Approach', () => {
  it('login', () => {
    cy.visit('/login')
 // these values email and pw shouldn't matter if mocking is done right
    cy.get('#email')
      .type('test')
      .should('have.value', 'test')

    cy.get('#password')
      .type('123456')
      .should('have.value', '123456')
    cy.server()
    cy.route({
      method: 'POST',
      url: 'http://localhost:9999/api/login', // this is the api that I send the request to 
    })
    cy.location('pathname', { timeout: 10000 }).should('eq', '/login');
    cy.title().should('include', 'Condeo')
    cy.get('#notification').should('exist')
  })
})

我没有在测试的详细信息中获得状态:

Method  Url                               Stubbed     Alias  #
POST    http://localhost:9999/api/login   Yes                -

【问题讨论】:

    标签: cypress


    【解决方案1】:

    你应该使用cypress的wait方法。

    您可以找到赛普拉斯文档here

    对于您的用例,请确保在访问链接之前启动服务器并定义路由。访问该链接后,使用 cy.wait() 方法,该方法将等待该 API 调用完成。

    例如。

    describe('Login Approach', () => {
      it('login', () => {
        cy.visit('/login')
     // these values email and pw shouldn't matter if mocking is done right
        cy.get('#email')
          .type('test')
          .should('have.value', 'test')
    
        cy.get('#password')
          .type('123456')
          .should('have.value', '123456')
        cy.server()
    
        cy.route({
          method: 'POST',
          url: 'http://localhost:9999/api/login', // this is the api that I send the request to 
        }).as('login') 
    
        cy.location('pathname', { timeout: 10000 }).should('eq', '/login');
        cy.title().should('include', 'Condeo')
        cy.get('#notification').should('exist')
        
        // Code which will try to visit the login API. 
        cy.wait('@login').then((xhr)=> {
           if(xhr.status === 200) {
               // Code to test when status is 200
           } else if(xhr.status === 400) {
               // Code to test when status is 400
           } else {
               // Code to test when status is none of the above.
           }
        })
      })
    })
    

    【讨论】:

    • 您好,感谢您的回复,我收到“cy.wait() 超时等待 5000 毫秒以等待对路由的第一个请求:登录。从未发生过请求。”
    • 是的,您必须访问该 URL。从页面或使用柏树请求。此外,cypress 默认不支持 fetch API。它只支持 XHR 请求。因此,如果您的页面使用 fetch API,请将 cypress.json 中的 experimentalFetchPolyfill 设置为 true
    • 谢谢,我将该道具添加到cypress.json。我在哪里可以找到有关访问 URL 的文档中的更多详细信息?
    • 如果你想向 cypress 请求,那么cy.request()。或者您必须从页面提交表单(应该有一些可以单击的按钮)。
    猜你喜欢
    • 2021-07-15
    • 1970-01-01
    • 2021-08-08
    • 2019-11-28
    • 1970-01-01
    • 2023-01-19
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多