local_storage.spec.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /// <reference types="cypress" />
  2. context('Local Storage', () => {
  3. beforeEach(() => {
  4. cy.visit('https://example.cypress.io/commands/local-storage')
  5. })
  6. // Although local storage is automatically cleared
  7. // in between tests to maintain a clean state
  8. // sometimes we need to clear the local storage manually
  9. it('cy.clearLocalStorage() - clear all data in local storage', () => {
  10. // https://on.cypress.io/clearlocalstorage
  11. cy.get('.ls-btn').click().should(() => {
  12. expect(localStorage.getItem('prop1')).to.eq('red')
  13. expect(localStorage.getItem('prop2')).to.eq('blue')
  14. expect(localStorage.getItem('prop3')).to.eq('magenta')
  15. })
  16. // clearLocalStorage() yields the localStorage object
  17. cy.clearLocalStorage().should((ls) => {
  18. expect(ls.getItem('prop1')).to.be.null
  19. expect(ls.getItem('prop2')).to.be.null
  20. expect(ls.getItem('prop3')).to.be.null
  21. })
  22. cy.get('.ls-btn').click().should(() => {
  23. expect(localStorage.getItem('prop1')).to.eq('red')
  24. expect(localStorage.getItem('prop2')).to.eq('blue')
  25. expect(localStorage.getItem('prop3')).to.eq('magenta')
  26. })
  27. // Clear key matching string in Local Storage
  28. cy.clearLocalStorage('prop1').should((ls) => {
  29. expect(ls.getItem('prop1')).to.be.null
  30. expect(ls.getItem('prop2')).to.eq('blue')
  31. expect(ls.getItem('prop3')).to.eq('magenta')
  32. })
  33. cy.get('.ls-btn').click().should(() => {
  34. expect(localStorage.getItem('prop1')).to.eq('red')
  35. expect(localStorage.getItem('prop2')).to.eq('blue')
  36. expect(localStorage.getItem('prop3')).to.eq('magenta')
  37. })
  38. // Clear keys matching regex in Local Storage
  39. cy.clearLocalStorage(/prop1|2/).should((ls) => {
  40. expect(ls.getItem('prop1')).to.be.null
  41. expect(ls.getItem('prop2')).to.be.null
  42. expect(ls.getItem('prop3')).to.eq('magenta')
  43. })
  44. })
  45. })