rino
rino

Reputation: 333

Retrieve value from json based on key provided using cypress

let expectedKey = 'Student';

cy.readFile('cypress/fixtures/applicationDetails.json').then((appDetails) => { 
    if(expectedKey === 'Student'){
        cy.get('app-screen').find('#code-details').should('have.text', appDetails.studentCode);
    }
    if(expectedDKey === 'Department'){
        cy.get('app-screen').find('#code-details').should('have.text', appDetails.departmentCode);
    }
    if(expectedKey === 'Paper'){
        cy.get('app-screen').find('#code-details').should('have.text', appDetails.paperCode);
    }
    if(expectedKey === 'Results'){
        cy.get('app-screen').find('#code-details').should('have.text', appDetails.resultsCode);
    }
}

I don't want to use these many if blocks as there will more keys in the future. Instead, I have to pick the required value for studentCode, departmentCode, paperCode, or resultsCode from JSON based on expectedKey. Any help please?

Upvotes: 3

Views: 1898

Answers (2)

jjhelguero
jjhelguero

Reputation: 2555

You can access object properties by dot notation (foo.bar) or bracket notation (foo['bar']). In your case, you'll have to ensure expectedKey matches a valid key in your object with assertion before the cy commands.

let expectedKey = 'studentCode';
cy.readFile('cypress/fixtures/applicationDetails.json').then((appDetails) => { 
  expect(appDetails, 'valid key').to.have.property(expectedKey)
  cy.get('app-screen').find('#code-details').should('have.text', appDetails[expectedKey]);
}

Upvotes: 1

Alapan Das
Alapan Das

Reputation: 18634

Assuming that you have the expectedKey inside the cy.readFile(), you can do like this:

  1. Create a custom command at cypress/support/commands.js:
Cypress.Commands.add('codeDetailsText', (expectedKey, appDetails) => {
  expectedKeyCode = expectedKey.toLowerCase() + 'Code'
  cy.get('app-screen')
    .find('#code-details')
    .should('have.text', appDetails[expectedKeyCode])
})
  1. In your test just write:
cy.readFile('cypress/fixtures/applicationDetails.json').then((appDetails) => {
  //Assuming expectedKey value is available here
  cy.codeDetailsText(expectedKey, appDetails)
})

Upvotes: 0

Related Questions