Accessing environment variables from Cypress Fixture

Viewed 1475

I have just started using Cypress for API test automation. There are some environment variables I'll like to access in my test files using Cypress.env. The cypress documentation lists the config file (cypress.json) as the obvious place to store environment variables.

I need to test numerous endpoints from over 40 data services companies. The business logic varies across all 40 services.

Hence, the objects in the "env" within cypress.json are numerous, so not manageable within one file.

My thought process to resolving this, is to create an environment variable file within Fixtures, storing the "env" objects for each of the data services. However I'm not sure if that's possible.

Also, is it possible to have more than one cypress.json file in one project?

Any advice will be most appreciated.

Here's a sample of my "env" variable for one data service provider.

{
    "env": {
        "dataService": "XXDataService",
        "companyRegNo": "XX4457ZZ",
        "language": "EN",
        "countryCode": "UK",
        "companyType": "Ltd",
        "companySearchName": "",
        "searchParams": "",
        "reportParams": "",
        "username": "",
        "password": "",
    }
}
2 Answers

I have met the same problem and finally make my own plugin.

cypress-template-fixtures

Usage

  1. npm i -D cypress-template-fixtures
  2. Add require('cypress-template-fixtures')(on, config); in the cypress/plugins/index.js.
module.exports = (on, config) => {
  require('cypress-template-fixtures')(on, config); // Add this line
  return config;
};
  1. Add the generated fixture folder cypress/fixtures.out/ into .gitignore.
  2. Use {{VAR_NAME}} in normal fixtures files in cypress/fixtures directory.

cypress/fixtures/example.json:

{
  "name": "{{NAME}}",
  "title": "{{TITLE}}",
  "email": "{{EMAIL}}",
  "body": "{{BODY}}"
}
  1. Provide VAR_NAME in cypress.json or cypress.env.json.
  2. Or provide CYPRESS_VAR_NAME in system or cypress-dotenv.

Read more docs here.

Refer Option-2-cypress-env-json

You can create your own cypress.env.json file that Cypress will automatically check. Values in here will overwrite conflicting environment variables in your configuration file (cypress.json by default).

Related