I don't know if this is the smartest way, but it appears to work.
It is to include the .env
in the cypress.config.ts
This would be the cleanest solution, where I just include all the variables once - and then they're accessible in all tests. But I can't get it to work.
I think this is my closest attempt:
import {defineConfig} from "cypress";
import * as dotenv from "dotenv";
dotenv.config();
const envVars = Object.keys(process.env).reduce((acc, key) => {
// console.log( 'LINE', key, process.env[key] ); // For debugging purposes
acc[key] = process.env[key];
return acc;
}, {});
export default defineConfig(
{
env: {
NODE_ENV: 'development',
...envVars
},
e2e: {
baseUrl: 'http://localhost:3000',
setupNodeEvents(on, config) {
// implement node event listeners here
},
specPattern: [
'src/**/*.cy.{js,jsx,ts,tsx}',
]
},
});
Then you can see all your env-variables in your tests like this:
Example test
it('Check create user works', () => {
// Prints all variables (just for show)
const obj = Cypress.env();
Object.keys( obj ).forEach( (key) => {
cy.log( key + ' => ' + obj[key] );
});
// Use it in a test
cy.request('GET', 'test-create-user').as('getConnection')
cy.get('@getConnection').should((response) => {
expect(response).to.have.property('status');
expect(response.status).to.eq(200);
expect(response.body.email).to.eq( Cypress.env('MY_TEST_USER') ); // This passes
});
})