Reputation: 155
I have sundry spec.js files to run. To increase tests performance and speed, I' ve created a first test file that login into my web service and store the token into an env variable called TOKEN that I' ve declared in cypress.json
{
"env": {
"TOKEN": ""
},
"viewportWidth": 1920,
"viewportHeight": 1080,
"responseTimeout": 90000,
"defaultCommandTimeout": 60000,
"requestTimeout": 60000
}
To do this I write the following code into the first test file:
describe('Setup', () => {
it('Should setup token', () => {
cy.request({
method: 'POST',
url: 'path/to/endpoint',
headers: {
'api_version': Cypress.env('API_VERSION')
},
body: {
userName: Cypress.env('USERNAME'),
password: Cypress.env('PASSWORD')
}
}).then((response) => {
Cypress.config('TOKEN', response.body.token)
});
});
});
The POST call works and it return and save the TOKEN in the cypress.json but It is available only for the first test file, when I go ahead with other test files (according to the documentation) the stored token value is deleted, because the Cypress.config('VAR_NAME', var_value)
works only on the test file that has used the statement.
I' ve tried to store the token value into a cookie and save permanently the cookie but the token is too long and cannot be stored into the cookie.
Is there a way to save the token into the cypress.json env PERMANENTLY?
Upvotes: 1
Views: 1027
Reputation: 31944
I think the simplest way to overcome the "only current spec" problem is to run your request in a before()
in /cypress/support/index.js
// support/index.js
before(() => {
cy.request({
method: 'POST',
url: 'path/to/endpoint',
...
}).then((response) => {
Cypress.config('TOKEN', response.body.token)
});
})
When I run a couple of simple validation tests
// support/index.js
Cypress.config('test', 'test1')
// tests 1 & 2
it('sees globally set config', () => {
expect(Cypress.config('test')).to.eq('test1')
})
it passes
Spec Tests Passing Failing Pending Skipped
┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│ √ config1.spec.js 89ms 1 1 - - - │
├────────────────────────────────────────────────────────────────────────────────────────────────┤
│ √ config2.spec.js 136ms 1 1 - - - │
└────────────────────────────────────────────────────────────────────────────────────────────────┘
√ All specs passed! 225ms 2 2 - - -
Upvotes: 2