当我尝试输入 OTP 代码(我从 API 获取)时,Cypress 显示错误 cypress 屏幕截图
cy.get('input[data-placeholder="OTP"]').type(getOtpCode(phoneNumber))
function getOtpCode(phone) {
var otpCode;
cy.request({
method: 'GET',
url: 'url'
}).then(resp => resp.body)
.then(data => data.find(element => element['body']['Message']['Phone'] == phone))
.then(phone => otpCode = phone['body']['Message']['CustomMessage']);
return otpCode;
}
如果我输入随机字符串而不是
getOtpCode()
,它就可以工作。你知道如何解决这个问题吗?
看起来您需要先执行
getOtpCode()
,因为异步cy.request()
。
该函数还需要返回
cy.request()
以允许在其后使用 .then()
。
function getOtpCode(phone) {
return cy.request({
method: 'GET',
url: 'url'
})
.then(resp => resp.body)
.then(data => data.find(element => element['body']['Message']['Phone'] == phone))
.then(phone => phone['body']['Message']['CustomMessage']);
}
getOtpCode(phoneNumber).then(otpcode => {
cy.get('input[data-placeholder="OTP"]').type(otpcode)
})
或者,将该功能更改为自定义命令。您不需要返回任何内容,因为 Cypress 将当前主题设置为
.then()
链中最后一个 cy.request()
的结果。
可以全局定义自定义命令。
cypress/support/commands.js
Cypress.Commands.add('getOtpCode', (phone) => {
cy.request({
method: 'GET',
url: 'url'
})
.then(resp => resp.body)
.then(data => data.find(element => element['body']['Message']['Phone'] == phone))
.then(phone => phone['body']['Message']['CustomMessage']);
})
测试
cy.getOtpCode(phoneNumber).then(otpcode => {
cy.get('input[data-placeholder="OTP"]').type(otpcode)
})
对于该功能,请执行以下操作:
cy.get('input[data-placeholder="OTP"]')
.should('be.visible')
.type(getOtpCode(phoneNumber))
function getOtpCode(phone) {
var otpCode
cy.request({
method: 'GET',
url: 'url',
})
.then((resp) => resp.body)
.then((data) =>
data.find((element) => element['body']['Message']['Phone'] == phone)
)
.then((phone) => (otpCode = phone['body']['Message']['CustomMessage']))
return cy.wrap(otpCode)
}
在您的测试文件中执行以下操作:
import className from '../path-to-js-file.js' //replace className with yours
const obj = new className() //replace className with yours
describe('Test Suite', () => {
it('Test Case', () => {
obj.getOtpCode(phone).then((otp) => {
cy.get('input[data-placeholder="OTP"]').type(otp)
})
})
})