setCookie command in cypress pretty much does what the name suggests. It sets the browser cookie.
Syntax
cy.setCookie(name, value)
cy.setCookie(name, value, options)
Arguments Used In setCookie:
- name: Name of the cookie to set
- value: Value for the cookie to set
- options
Options In setCookie:
- Log: Displays command in the command log.
- Domain: Used to set the domain the cookie is visible to, and the default is window.location.hostname.
- Expiry: Since the Unix epoch is used to set when the cookie expires, the default is 20 years from now.
- HttpOnly: Used to specify whether the cookie is HTTP only cookie.
- Path: Cookie path.
- Secure: Secure cookie.
- Timeout: Time to wait for my.setCookie() to resolve.
- sameSite: Cookie's SameSite value. If set should be one of lax, strict, or no_restriction.
Example
Let us try to set a cookie and assert its value to be equal to the set value of the cookie.
describe('Cookie',()=>{
it('SetCookie',()=>{
cy.getCookies().should('be.empty')
cy.setCookie('session_id', '77eiincnw3ne88fsfdscvs')
cy.getCookie('session_id').should(
'have.property',
'value',
'77eiincnw3ne88fsfdscvs'
)
})
}
- So we are ensuring that the cookie is empty first and setting the cookie using the setCookie command to some random cookie value.
- Using the have.property value, we assert the cookie value of the session_id name we assigned it to.
- So we can see that can assert that the cookie values are identical for session_id.
Rules For Using setCookie():
- cy.setCookie() should be chained with cy.
- cy.setCookie() only runs assertions chained once and won't retry.
- cy.setCookie() never times out.
- Log in to post comments