You could define them at the describe() or context() level, if the data will be the same for all tests in those blocks. This is similar to what you've already done in your it() block.
describe('some test', { env: { foo: 'bar' } }, () => {
it('logs foos value', () => {
cy.log(Cypress.env('foo'); // logs 'bar'.
});
});
You could also store them in your cypress.json or cypress.env.json files.
// cypress.json
{
...
'env': {
'foo': 'bar'
}
...
}
// cypress.env.json
{
'foo': 'bar'
}
Cypress will pick up variables included in cypress.json or cypress.env.json automatically, so no additional setup would be required. Note: Environment variables stored in cypress.env.json will override any set in cypress.json.
Either way, after defining the variables at a higher scope than the it() block, you can set them in the before() or beforeEach() of your block.
// assumes value is set in cypress.json
describe('some tests', () => {
let foo: string;
before(() => {
foo = Cypress.env('foo');
});
it('logs foo value', () => {
cy.log(foo); // logs 'bar'
});
});
EDIT: After discussion, it seems like the actual question being asked is how the data can be set and easily used. I think the easiest way would just be to set the data in the beforeEach().
describe('some test', () => {
let foo: string;
beforeEach(() => {
foo = Cypress.env('foo');
})
it('logs bar', { env: { foo: 'bar' } }, () => {
cy.log(foo); // logs 'bar'
});
it('logs baz', { env: { foo: 'baz' } }, () => {
cy.log(foo); // logs 'baz'
});
});
It may also be valuable to set a default value, in case you have a use case that you're using > 50% of the time.
...
let foo: string;
beforeEach(() => {
foo = Cypress.env('foo') ?? 'defaultValue'
});
...