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

How to set a sessionStorage in Cypress?

1个答案

1

Setting sessionStorage in Cypress can be achieved in multiple ways, depending on when you want to set it during test execution. Here are some methods to set sessionStorage:

Directly in the Test

You can directly set sessionStorage during test execution using Cypress's API. See the example below:

javascript
describe('SessionStorage Test', () => { it('should set an item in sessionStorage', () => { cy.visit('http://example.com'); // replace with the page you are testing cy.window().then((win) => { win.sessionStorage.setItem('key', 'value'); }); }); });

In this example, cy.window() is used to obtain a reference to the current window, enabling you to manipulate its sessionStorage, such as setting a key-value pair with setItem.

Setting via Cypress Commands

You can create custom Cypress commands to set sessionStorage, making your code more modular and reusable. See the example below:

javascript
Cypress.Commands.add('setSessionStorage', (key, value) => { cy.window().then((win) => { win.sessionStorage.setItem(key, value); }); }); describe('SessionStorage Test', () => { it('should set an item in sessionStorage using a custom command', () => { cy.visit('http://example.com'); // replace with the page you are testing cy.setSessionStorage('key', 'value'); }); });

In this example, we add a new command named setSessionStorage using Cypress.Commands.add to set sessionStorage.

Setting Before the Test

If you want to set sessionStorage before test execution begins, use beforeEach to ensure it is set before each test case:

javascript
describe('SessionStorage Test', () => { beforeEach(() => { cy.visit('http://example.com'); // replace with the page you are testing cy.window().then((win) => { win.sessionStorage.setItem('key', 'value'); }); }); it('should have an item in sessionStorage', () => { cy.window().then((win) => { const item = win.sessionStorage.getItem('key'); expect(item).to.equal('value'); }); }); });

In this example, the beforeEach block runs before each test case, setting sessionStorage.

Note

When using Cypress to manipulate sessionStorage, remember that sessionStorage is page-specific. This means you must set it after cy.visit() or after the page has fully loaded; otherwise, when the page loads, a new sessionStorage instance may be created, overriding your settings.

2024年6月29日 12:07 回复

你的答案