Cypress localStorage commands
Extends Cypress' cy commands with localStorage methods. Allows preserving localStorage between tests.
You want to preserve localStorage between Cypress tests.
This solution allows you to use all browser localStorage methods through Cypress commands, and preserve it between tests.
This module is distributed via npm which is bundled with node and should be installed as one of your project's devDependencies:
npm i --save-dev cypress-localstorage-commands
cypress-localstorage-commands extends Cypress' cy command.
Add this line to your project's
You can now use all next commands:
Save current localStorage values into an internal "snapshot":
Restore localStorage to previously "snapshot" saved values:
Clear localStorage "snapshot" values:
Get localStorage item. Equivalent to
localStorage.getItem in browser:
Set localStorage item. Equivalent to
localStorage.setItem in browser:
Remove localStorage item. Equivalent to
localStorage.removeItem in browser:
Preserving local storage between tests
saveLocalStorage to save a snapshot of current
localStorage at the end of one test, and use the
restoreLocalStorage command to restore it at the beginning of another one. The usage of
afterEach is recommended for this purpose.
Cookies button example
Next example shows how this package can be used to test a "cookies button" (which theorically sets a flag into
localStorage and can be clicked only once)
Note the usage of
localStoragebetween all tests. Also
clearLocalStorageSnapshotis used in the
beforestatement to avoid possible conflicts with other test files preserving localStorage.
Based on the previous example, assertions could be added to check values of
Usage with TypeScript
For those writing TypesScript tests in Cypress, this package includes TypeScript declarations.
Add "cypress-localstorage-commands" to the
types property of the
Or reference the package in the files using it:
MIT, see LICENSE for details.