Reputation: 2619
I have created a Cypress command to fetch me a JWT token from my GQL API. I then set the token as a cookie to use in my tests that require authentication.
Here is my login command:
export function login(username, password) {
const { apiUrl: url } = Cypress.env();
cy.request({
method: 'POST',
url,
body: {
operationName: 'signin',
headers: {
'content-type': 'application/json'
},
query:
`mutation signin($email: String!, $password: String!) {
signin(input: {email: $email, password: $password}) {
id
token
__typename
}
}`,
variables: { email: username, password: password }
}
})
.then(response => {
const { token } = response.body.data.signin;
cookie.set('token', token, { expires: 10000000 });
cy.wait(3000);
});
}
I can see when I run the login
command the cookie is set but when my test tries to visit a page within my app the cookie disappears.
describe('Entity Page', () => {
before(() => {
const { username, password } = Cypress.env();
cy.login(username, password);
cy.addEntity(newEntityId, {});
cy.wait(3000);
cy.get('@entityId').then(entityId => {
cy.visit(`/entity/${entityId}`)
cy.wait(6000)
});
});
By the time I get to addEntity
the cookie disappears and I am unauthenticated. Is there something I need to do to persist cookies? I tried Cypress.Cookies.preserveOnce
but this had no effect
I also tried adding the below to my support/index.js
but the cookie is still removed.
Cypress.Cookies.defaults({
preserve: 'token'
})
Upvotes: 0
Views: 779
Reputation: 31924
Try it with cy.setCookie(name, value)
docs.
It has a couple of defaults that might help.
Upvotes: 1