如何运行循环函数直到从 cypress 项目中的 API 获取价值

问题描述 投票:0回答:1

我必须循环一个函数才能从 cypress 项目中的 API 获取值。 (我们会多次调用API,直到获得值。

let otpValue = '';
const loopFunc = () => {
    cy.request({
      method: 'GET',
      url: 'http://tesurl/api/otp/getotp',
    }).then((res) => {
      expect(res.status).to.equal(200);
      res.body.OTPCode !== null ? (otpValue = res.body.OTPCode) : loopFunc();
      
    });
  };
cy.get('otpinput').type(otpValue)

但是循环功能不起作用。我期待直到获得“OTPCode”值不为空时循环函数才会运行。

提前致谢。

javascript typescript ecmascript-6 cypress
1个回答
0
投票

在 Cypress 中,您需要小心异步操作,尤其是在处理请求时。您可以使用 Cypress 的重试机制与自定义断言相结合来等待具有非空 OTP 代码的 API 响应,而不是使用递归循环。以下是如何实现此目标的示例:

let otpValue = '';

const getOtp = () => {
  return cy.request({
    method: 'GET',
    url: 'http://testurl/api/otp/getotp',
  });
};

const waitUntilOtpNotNull = () => {
  return getOtp().then((res) => {
    expect(res.status).to.equal(200);

    if (res.body.OTPCode !== null) {
      otpValue = res.body.OTPCode;
    } else {
      // Retry until OTPCode is not null
      cy.wait(1000); // Adjust the wait time as needed
      waitUntilOtpNotNull();
    }
  });
};

// Usage
waitUntilOtpNotNull().then(() => {
  // Once the OTP is obtained, type it into the input
  cy.get('otpinput').type(otpValue);
});
© www.soinside.com 2019 - 2024. All rights reserved.