Create an angular environment for test purpose
This is a step-by-step guide to explain how to run end to end tests in a custom environment, using angular 9 and ng-cli.
An angular workspace generated with the angular CLI has a specific structure, which needs to be consistent with the angular.json
configuration. This configuration provides what is needed to build each project. In this case I want to provide a different environment to execute my e2e tests.
A default angular project template, created with the ng CLI, comes with a dev environment (environment.ts
) and a production environment (environment.prod.ts
).
The command ng e2e <project>
, or nx e2e <project>
if you use Nx, serves the application in the development environment and executes the tests.
So what I want is to create a new environment, let's say environment.test-e2e.ts
, and use it to serve my application.
In the configuration angular.json
, in the section of the e2e project, I added the new environment in the configuration in this way:
"my-project-e2e": {
"root": "apps/my-project-e2e",
"sourceRoot": "apps/my-project-e2e/src",
"projectType": "application",
"architect": {
"e2e": {
"builder": "@nrwl/cypress:cypress",
"options": {
"cypressConfig": "apps/my-project-e2e/cypress.json",
"tsConfig": "apps/my-project-e2e/tsconfig.e2e.json",
"devServerTarget": "my-project:serve"
},
"configurations": {
"production": {
"devServerTarget": "my-project:serve:production"
},
"test-e2e": {
"devServerTarget": "my-project:serve:test-e2e"
}
}
},
...
}
}
At this point, you need to provide the information in your project configuration about how to build and serve with this environment. So in the project section, you need to add the test-e2e configuration for the build and serve commands.
"my-project": {
...
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
...
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "apps/my-project/src/environments/environment.ts",
"with": "apps/my-project/src/environments/environment.prod.ts"
}
],
...
]
},
"test-e2e": {
"fileReplacements": [
{
"replace": "apps/my-project/src/environments/environment.ts",
"with": "apps/my-project/src/environments/environment.test-e2e.ts"
}
]
}
}
},
"serve": {
...
"configurations": {
"production": {
"browserTarget": "my-project:build:production"
},
"test-e2e": {
"browserTarget": "my-project:build:test-e2e"
}
}
},
}
},
Now all you have to do to execute your end to end test in the test-e2e
environment is to run the CLI specifying the configuration:
ng e2e my-project --configuration=test-e2e