我想使用 cypress 中的 cy.intercept 从 API 响应中获取 OrderID

Kru*_*iya 0 automated-tests web-api-testing cypress

我想从 API 响应中获取订单 ID。当我单击“创建订单”按钮时,它将发送 POST API 请求并返回我想要保存在 JSON 文件中的 ID。

这是我的订单创建代码。

cy.clickOnElement(practicePageSelectors.CreateOrder).click(); // click on add Rx button
cy.readFile('cypress/fixtures/Data.json').then((profile) => {
   cy.searchPatients(practicePageSelectors.searchPatient1, profile.Patient_fullName);
})
cy.searchDoctors(); // search for the doctor
cy.clickOnElementUsingXpath(practicePageSelectors.nextButtonId); // click on the next button
cy.clickOnElement(practicePageSelectors.createOnetimeOrder)
cy.searchMedicine() //search for Medicine
cy.clickOnElementUsingXpathfirst(practicePageSelectors.addMedicine); // click on add button
cy.clickOnElementUsingText(practiceData.paymentButtonName, practiceData.buttonTag); // click on skip payment button
cy.clickOnElementUsingXpath(practicePageSelectors.submit_CreateOrderButton)
Run Code Online (Sandbox Code Playgroud)

我尝试过这样的事情

cy.intercept({
      method: 'POST',
      url: 'https://ibis-dev.droicelabs.us/api/dispenser/orders/',
    }).then((responce)=>{
      let body = JSON.parse(responce.body)
      cy.log(body)
    })
Run Code Online (Sandbox Code Playgroud)

我不知道如何使用intercept。请指导我

Luk*_*rys 5

您必须在进行 http 调用之前注册拦截器,然后等待测试中的数据。

这应该发生在before挂钩中或在实际测试用例之上。

cy.intercept({
  method: 'POST',
  url: 'https://ibis-dev.droicelabs.us/api/dispenser/orders/',
}).as('ordersCall')
Run Code Online (Sandbox Code Playgroud)

然后在需要ID的地方

cy.wait('@ordersCall')
  .its('response.body')
  .then((body) => {
    // parsing might be not needed always, depends on the api response
    const bodyData = JSON.parse(body) 
    cy.log(bodyData)
  })
Run Code Online (Sandbox Code Playgroud)

旁注:cy.fixture()直接从fixtures目录读取 - 无需使用cy.readFile