In frontend automation testing with Cypress, checking the values of sessionStorage is a common requirement. Cypress provides both direct and indirect methods to access and check sessionStorage. The following is a specific example and steps explaining how to check sessionStorage values in Cypress tests.
1. Accessing sessionStorage
First, to access the browser's sessionStorage in Cypress, use the cy.window() command to access the window object. Then, retrieve the sessionStorage object using the its command.
javascriptcy.window().its('sessionStorage')
2. Retrieving Specific sessionStorage Values
Once you have the sessionStorage object, use the invoke() command to call the getItem method for specific items. For example, to check the value of the item named 'userInfo' in sessionStorage:
javascriptcy.window() .its('sessionStorage') .invoke('getItem', 'userInfo') .then((userInfo) => { // Use userInfo here });
3. Asserting Values in sessionStorage
After retrieving the value from sessionStorage, perform assertions to verify it meets expected criteria. For instance, if you expect 'userInfo' to store the JSON string {"name":"John","age":30}:
javascriptcy.window() .its('sessionStorage') .invoke('getItem', 'userInfo') .then((userInfo) => { const user = JSON.parse(userInfo); expect(user.name).to.eq('John'); expect(user.age).to.eq(30); });
4. Example: Complete Test Case
Below is a complete Cypress test case demonstrating how to verify user information stored in sessionStorage after login:
javascriptdescribe('Session Storage Test', () => { it('should store the correct user info in sessionStorage', () => { // Assume this is the login step cy.visit('/login'); cy.get('#username').type('John'); cy.get('#password').type('password123'); cy.get('#login-button').click(); // Check sessionStorage cy.window() .its('sessionStorage') .invoke('getItem', 'userInfo') .then((userInfo) => { const user = JSON.parse(userInfo); expect(user.name).to.eq('John'); expect(user.age).to.eq(30); }); }); });
Summary
Through these steps, you can effectively check sessionStorage values in Cypress. This approach is valuable for verifying browser storage of necessary information in scenarios like user login, configuration changes, or other contexts.