CYPRESS-在输入API请求的值时出错



当我尝试键入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(),它的工作。你知道如何解决这个问题吗?谢谢你的帮助:)

对于函数这样做:

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)
})
})
})

看起来您需要先执行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将当前主题设置为cy.request()链中最后一个.then()的结果。

自定义命令可以全局定义。

柏树/支持/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)
})

相关内容

最新更新