Consider this Cypress test that tries to authenticate using a token and then checks the user profile page.
describe('Token Auth Test', () => {
it('should load profile with valid token', () => {
cy.visit('/profile', {
onBeforeLoad(win) {
win.localStorage.setItem('authToken', 'valid-token-123')
}
})
cy.get('[data-cy=user-name]').should('contain.text', 'Alice')
})
})What will happen when this test runs?
describe('Token Auth Test', () => { it('should load profile with valid token', () => { cy.visit('/profile', { onBeforeLoad(win) { win.localStorage.setItem('authToken', 'valid-token-123') } }) cy.get('[data-cy=user-name]').should('contain.text', 'Alice') }) })
Think about when localStorage is set and how Cypress commands work.
The token is correctly set in localStorage before the page loads, so the app reads it and shows the user name 'Alice'. The selector matches the element, so the assertion passes.
You want to check that the token 'abc123' is saved in localStorage under the key 'authToken' after login.
Which Cypress assertion is correct?
cy.window().then(win => { // assertion here })
Remember how to get an item from localStorage and check its value.
localStorage.getItem('authToken') returns the string value stored. Option B correctly compares it to 'abc123'. Options B and D incorrectly access localStorage as an object property, which is not reliable. Option B expects undefined, which is wrong.
You want to select the login button in your Cypress test to trigger token-based login.
Which locator is best for maintainability and accessibility?
Think about selectors that are stable and do not depend on styling or text.
Using a custom data attribute like data-cy is best practice because it is stable and does not change with styling or text changes. Option D depends on an ID which might change. Option D depends on button text which can change or be localized. Option D depends on CSS class which might change.
Look at this test code snippet:
cy.visit('/dashboard')
cy.window().then(win => {
win.localStorage.setItem('authToken', 'token123')
})
cy.get('[data-cy=welcome-msg]').should('contain.text', 'Welcome')Why does the test fail to show the welcome message?
Consider when localStorage is set relative to page load.
The token is set after cy.visit loads the page, so the app does not detect the token on initial load and does not show the welcome message. To fix, set the token before page load using onBeforeLoad.
Your app uses short-lived tokens and refresh tokens to maintain authentication.
Which approach is best to handle token refresh automatically in Cypress tests?
Think about how to keep tokens fresh and tests realistic.
Using Cypress tasks to call backend refresh endpoints allows tests to get fresh tokens dynamically, keeping tests realistic and secure. Stubbing tokens (A) or manually setting tokens (B) can cause stale tokens and false positives. Ignoring refresh (D) risks test failures due to expired tokens.