乐闻世界logo
搜索文章和话题

How to set a token in localStorage before test in Cypress

1个答案

1

When using Cypress for end-to-end testing, handling authentication is a common task. In some cases, applications may use localStorage to store tokens for maintaining user login sessions. Setting localStorage in Cypress allows you to simulate a logged-in user state before tests begin, bypassing the login screen and directly testing core application functionality.

To set localStorage in Cypress tests, you can use Cypress's cy.setLocalStorage() command. Here is a simple example demonstrating how to set the token before testing:

Example:

Assume we have an application where users store a token named auth_token in localStorage after logging in. We need to set this token before each test execution.

javascript
describe('User Dashboard Test', () => { beforeEach(() => { // Set the token in localStorage before each test cy.setLocalStorage('auth_token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); // Verify that the token is set in localStorage before proceeding cy.getLocalStorage('auth_token').should('eq', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'); // Visit the user's dashboard page cy.visit('/dashboard'); }); it('Should display user-specific data', () => { cy.contains('Your Data').should('be.visible'); }); });

In the above code, the beforeEach hook ensures that auth_token is set in localStorage before each test starts. This enables the application to recognize the token when tests access authenticated pages (such as the user dashboard), allowing tests to proceed without manual login.

This approach improves test efficiency and reduces execution time by bypassing the login process and directly testing core functionality. Additionally, it allows reusing the same login state across different test cases, making test scripts more concise and maintainable.

2024年7月23日 13:35 回复

你的答案