Reputation: 3
I am trying to get a value from response body and then using it in another it-s in Cypress 10. I have created custom cy.task for get and set global variable, but it's not a good solution when I need for example 10 values from previous test:
await cy.task("getValue", {key: "one"}).then((one){
await cy.task("getValue", {key: "two"}).then((two){
await cy.task("getValue", {key: "three"}).then((three){
await cy.task("getValue", {key: "four"}).then((four){
...
if(one === null && two === null && three == null && four == null){
do smth
}
});
});
});
});
Another solution is get value from cy.task and save it into local variable:
let one_helper;
let two_helper;
let ...
cy.task("getValue", {key: "one"}).then((one){
one_helper = one;
}
cy.task("getValue", {key: "two"}).then((two){
two_helper = two;
}
...
if(one_helper == null && two_helper == null){
do smth
}
But it's not a good solution for me because I have a lots of values from previous response.
Upvotes: 0
Views: 946
Reputation: 18586
You can use Cypress.env() to save any value globally.
Cypress.env('somekey', 'somevalue') //saves the value
Cypress.env('somekey') //gets 'somevalue'
Upvotes: 1
Reputation: 32148
You could pass an array of keys to one task call.
const { defineConfig } = require('cypress')
const store = {}
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('task', {
getValue(keys) {
if (typeof keys === 'string') { // only a single key?
keys = [keys] // arrayify it
}
return keys.map(key => store[key])
},
})
}
}
})
Upvotes: 0