Let's say you need to pass some values to Cypress tests. You should use Cypress environment variables (not to be confused with process environment variables) and read them using Cypress.env command. For example, you could pass login information to your specs, as describe in Keep passwords secret in E2E tests. On CI, you could store the value as a secret, and then pass it to Cypress. The syntax differs, but for example on GitHub Actions you could use something like this:
1 | npx cypress run --env userName=${{ secrets.USERNAME }},password=${{ secrets.PASSWORD }} |
It all works if you only have a few simple values to pass. If you have multiple values, or if they are complex JSON objects, passing them via command line is bound to break due to parsing and quotes. Luckily, there are other ways, and this blog post shows one good way for GitHub Actions.
🎁 You can find the source code and see the executed GitHub Actions in the repo bahmutov/cypress-env-example.
First, you could put the values into env
key of the cypress.json
file
1 | { |
The test in our case simply checks the values.
1 | it('has valid env values', () => { |
I ran the test locally and it shows the expected values from the cypress.json
file
To better separate Cypress own configuration values from the user's own values, you could move the env
object from cypress.json
to cypress.env.json
file.
1 | { |
1 | {} |
The test passes the same way.
Continuous Integration
Now let's move to CI. We probably will use different values when running the tests. I will add these values as a secret. GitHub Actions allow multiline secrets, so I add a complete JSON object there.
Now let's write our workflow file. I will skip using my own Cypress reusable workflows and instead will use the plain Cypress GitHub Action.
1 | name: ci |
As you can see, we echo the secret's value and redirect it to the "cypress.env.json" file, overwriting the existing file. Then we run the tests and save the screenshots folder produced by the tests. A typical run finishes successfully.
We download the zip archive with the screenshots by clicking on it. The Test Runner shows the values from the CI secret were used in the test.
Pretty sweet.