0

How can I store Regex value in cypress config file? I'm using the following regex in the test:

cy.get('.company_highlight').contains(/JPM|Morgan/g)

When I put this value in the config file I have to store it as string, but then the test will fail since its a string value.

I tried directl inputting that value into config file:

cypress.json

{
   "Company":/JPM|Morgan/g
}

And in the test:

cy.get('.company_highlight').contains(Cypress.config().Company)

Which gives error: Unexpected token / in JSON

Alex T
  • 3,529
  • 12
  • 56
  • 105
  • Regex literals aren't supported in JSON. You'd have to store it in the JSON as a *string*, with appropriate escapes, then create a `new RegExp` from it per https://stackoverflow.com/q/874709/3001761. See also https://stackoverflow.com/q/8328119/3001761. – jonrsharpe Jan 15 '21 at 09:25

1 Answers1

2

JSON doesn't support regex literals like you'd write it in JavaScript. And string values have to be wrapped in double quotes.

I can imagine you can still use what JavaScript has to offer when it comes to regexes:

let re = new RegExp(Cypress.config().Company, 'g')

and the json file:

{
   "Company": "(JPM|Morgan)"
}
pavelsaman
  • 7,399
  • 1
  • 14
  • 32