Home > Blockchain >  CYPRESS- error during type a value from API request to input
CYPRESS- error during type a value from API request to input

Time:07-11

When I try to type OTP code (I get it from API), cypress shows an error cypress screenshot

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

If i typed a random string instead getOtpCode() it's working. Do you know how to resolve that problem? Thanks for any help :)

CodePudding user response:

For the function do this:

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

In your test file do this:

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

CodePudding user response:

It looks like you need to perform getOtpCode() first, because of the async cy.request().

Also the function needs to return the cy.request() to allow .then() to be used after it.

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

Alternately, change the function to a custom command. You will not need to return anything as Cypress sets the current subject to the result of the last .then() in the cy.request() chain.

The custom command can be defined globally.

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']);
})

test

cy.getOtpCode(phoneNumber).then(otpcode => {
  cy.get('input[data-placeholder="OTP"]').type(otpcode)
})
  • Related