Search code examples
javascriptcypress

Custom Cypress command doesn't return the expected value


I'm writing the follow custom Cypress command in order to get the value of an element in my html page. The idea is to do this:

MyCompanyAPI.API.Fields.getById('main').value

What ist fast the same as

window.document.getElementById().value

But I need to use the first option and in a Cypress command. So I did something like that:

Cypress.Commands.add('getValue', (id) => {

cy.window().then((win) => {
    const myCompanyAPI = win.MyCompanyAPI;
    if (!hybridForms) {
      cy.log('MyCompanyAPI object not found in window.');
      return cy.wrap(undefined);
    }
  
    return cy.wrap(myCompanyAPI.API.Fields).invoke('getById', id).then((result) => {
      const value = result && result.value;
      cy.log(`Value for ${id}:`, value);
  
      if (value === undefined) {
        cy.log(`API call for ${id} returned undefined.`);
      }
  
      return cy.wrap(value);
    });
  });

});

The win.MyCompanyAPI and myCompanyAPI.API.Fields really exist inside win. But when I try to call the function getByID() inside myCompanyAPI.API.Fields, the result is just:

Command: log index-a10e15b7.js:103972 Message: API call for #main returned undefined. index-a10e15b7.js:103972 Args:

I've tried in many ways. One of them like that, in order to debbug:

Cypress.Commands.add('getValue', (id) => {

    cy.window().then((win) => {
        const hybridForms = win.HybridForms;
        if (!hybridForms) {
          cy.log('HybridForms object not found in window.');
          return cy.wrap(undefined);
        }
      
        const api = hybridForms.API;
        if (!api) {
          cy.log('API not found in HybridForms.');
          return cy.wrap(undefined);
        }
      
        const fields = api.Fields;
        if (!fields) {
          cy.log('Fields not found in API.');
          return cy.wrap(undefined);
        }
      
        const getById = fields.getById;
        if (!getById) {
          cy.log('getById not found in Fields.');
          return cy.wrap(undefined);
        }
      
        const value = getById(id);
        if (!value) {
          cy.log(`Value for ${id} is undefined.`);
          return cy.wrap(undefined);
        }
      
        const finalValue = value.value;
        cy.log(`Final value for ${id}:`, finalValue);
      
        return cy.wrap(finalValue);
      });
      
      
      
  });

But the result ist also: Value for #main is undefined..

Could anyone here help me in this issue?

Thanks in advance!

I need to receive the value of

MyCompanyAPI.API.Fields.getById('main').value

But inside a Cypress custom command


Solution

  • It looks like you might be passing "#main" as the argument to getValue but it expects "main" since getElementById does not need the # specifier. That selector syntax is only relevant to methods like querySelector whereas getElementById is already looking for IDs so the # discriminator is not relevant.