'how to exclude few files/folder from using preserved cypress cookies
I am trying to preserve cookies in index.js file :
Cypress.Cookies.defaults({
preserve: ['session_id', 'remember_token'],
})
But I want to exclude few files such as login/authentication files from using the preserved cookies because I want to test real login here.
I see that cypress provides something like:
Cypress.Cookies.defaults({
preserve: (cookie) => {
// implement your own logic here
// if the function returns truthy
// then the cookie will not be cleared
// before each test runs
},
})
But I am not sure how to exclude a folder/files inside this. If someone has an idea kindly help. Or if there is any other better option to exclude files from using preserved cookies do let me know
Solution 1:[1]
I don't believe there is a way to exclude Cookies based on what spec file is running. Instead, you could clear them in the specs that you do not want values, and create a helper to check they are set in the specs.
// support/index.js
...
Cypress.Cookies.defaults({
preserve: ['session_id', 'remember_token'],
})
Cypress.Commands.add('setDefaultCookies', () => {
const defaults = { 'session_id': 'foo', 'rememberToken': 'bar' }
cy.getCookies().then((cookies) => {
for (const [key, value] of Object.entries(defaults) {
// use `find` to check if we have the specified cookie
const found = cookies.find(x => x.name === key);
if (!found) {
cy.setCookie(key, value);
}
};
});
});
...
// auth.spec.js (doesn't want cookies)
...
before(() => {
cy.clearCookies();
});
...
// foo.spec.js (wants cookies)
...
before(() => {
cy.setDefaultCookies();
});
...
Solution 2:[2]
In the Cypress.Cookies.defaults preserve function you can return true or false depending on the cookie properties and the current spec properties.
Cypress.Cookies.defaults({
preserve: (cookie) => {
const isLogin = Cypress.spec.name.contains('login') || // e.g login.spec.js
Cypress.spec.relative.contains('login'); // e.g /login-tests/...
if (cookie.name === 'token' && isLogin {
return false
} else {
return true
}
},
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | agoff |
| Solution 2 | Fody |
