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

How to clear local storage in Cypress test?

1个答案

1

Clearing local storage in Cypress is an important step, especially when performing end-to-end (E2E) tests that require verifying application state or user authentication information. Cypress provides several methods to clear local storage. Here are some common approaches:

1. Using the cy.clearLocalStorage() Method

The most straightforward approach is to use Cypress's cy.clearLocalStorage() command. This command can be invoked at any point during test execution to clear all local storage data in the browser. You can call it within the beforeEach hook to ensure each test case runs in a clean environment:

javascript
describe('User login flow test', () => { beforeEach(() => { // Clear all local storage cy.clearLocalStorage(); }); it('Login should succeed and navigate to user homepage', () => { cy.visit('/login'); cy.get('input[name="username"]').type('testuser'); cy.get('input[name="password"]').type('testpassword'); cy.get('button[type="submit"]').click(); cy.url().should('include', '/user-home'); }); });

2. Clearing Specific Local Storage Items

If you only need to clear specific items in local storage, pass a regular expression or string as a parameter to cy.clearLocalStorage(), allowing precise control over which data is cleared:

javascript
describe('Saving search history', () => { beforeEach(() => { // Clear only local storage items related to search cy.clearLocalStorage(/searchHistory/); }); it('Should save user search history', () => { cy.visit('/search'); cy.get('input[name="search"]').type('Cypress'); cy.get('form').submit(); // Verify search history is saved in local storage cy.window().then((win) => { expect(win.localStorage.getItem('searchHistory')).to.include('Cypress'); }); }); });

3. Clearing Local Storage After Test Completion

Sometimes, you may want to preserve the local storage state during test execution until after all tests complete. This can be achieved by calling cy.clearLocalStorage() in the afterEach or after hooks:

javascript
describe('Multiple test cases involving local storage', () => { afterEach(() => { // Clear local storage after each test cy.clearLocalStorage(); }); it('Test case 1', () => { // Perform operations affecting local storage }); it('Test case 2', () => { // Perform other operations affecting local storage }); });

By using these methods, you can effectively manage local storage in Cypress tests to ensure each test case runs in the expected environment state.

2024年6月29日 12:07 回复

你的答案