Search code examples
cypresslodashgherkincypress-cucumber-preprocessor

Accessing dynamically nested values in Cypress Gherkin Preprocessor


How can you access or modify nested objects with Cypress-Gherkin?

Let's assume you would like to change values of a fixture or validate a response.

You know the path of the keys in the nested object and you would like to add as variable from the Gherkin file, but you realize the nested value cannot set/access easily in JavaScript (at least dynamically):

Accessing nested JavaScript objects and arrays by string path


Solution

  • Luckily Cypress automatically includes lodash: https://docs.cypress.io/api/utilities/_#Syntax

    so you don't have to add an extra dependency:

    and the answer will be simpler, than I ever expected - but earlier I didn't find it, therefore I am sharing it now:

    After you read the fixture (=payloadToModify), you can easily modify:

    Cypress._.set(payloadToModify, pathOfKeyFromGherkin, newValueFromGherkin)
    

    or get its value

    Cypress._.get(payloadToModify, pathOfKeyFromGherkin)