How to run Protractor e2e tests with different environment variables (Angular 6)

Shaman picture Shaman · Sep 26, 2018 · Viewed 8.5k times · Source

In e2e test I want to have environment variable similar to the one as in Angular app. Looks like e2e test project builder "builder": "@angular-devkit/build-angular:protractor" does not support file replacements (unlike builder for web app):

"fileReplacements": [{
  "replace": "apps/web/src/environments/environment.ts",
  "with": "apps/web/src/environments/environment.prod.ts"
}]

So using Angular CLI ng e2e command I can switch configurations (or projects in angular.json) and in project configuration I can specify different Protractor configuration files protractor.conf.js. My question is: how can I get in e2e test any variable which will be different in configuration files or any other file, similar to the environment.ts file(s) in the app?

Answer

Shaman picture Shaman · Oct 4, 2018

So I ended up by using protractor.conf.js for environment variables. Main advantage - no need to use any third party lib.
1. Create a Protractor config file for each environment. In params specify your variables:

'protractor.conf.js'
...
  params: {
    postDeploy: false,
    credentials: {
      username: 'Test',
      password: 'Password'
    },
...

Second Protractor config file can use the first one as default and contain only overrides (to avoid duplicates in configs):

'protractor-dev.conf.js'

const defaultConfig = require('./protractor.conf');
let devConfig = {
  params: {
    postDeploy: true,
    credentials: {
      username: 'DevTest',
      password: 'DevPassword'
    }
  }
};
exports.config = Object.assign(defaultConfig.config, devConfig);
  1. Use configurations in angular.json for e2e project:
...
    "myproject-e2e": {
      "root": "",
      "sourceRoot": "",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "apps/myproject-e2e/protractor.conf.js",
            "devServerTarget": "myproject:serve"
          },
          "configurations": {
            "dev": {
              "protractorConfig": "apps/myproject-e2e/protractor-dev.conf.js",
              "devServerTarget": "",
              "baseUrl": "https://mywebsite.com"
            },
  1. Switch configurations in command line using -c or --configuration parameter
ng e2e myproject-e2e -c dev

You can also overwrite some parameters in the command line:

ng e2e myproject-e2e -c dev --baseUrl=https://mywebsite1.com

4. And finally in e2e tests itself, you can use any parameter from config:

browser.params.postDeploy
browser.params.credentials.username