GithubHelp home page GithubHelp logo

javierbrea / cypress-localstorage-commands Goto Github PK

View Code? Open in Web Editor NEW
178.0 3.0 9.0 9.75 MB

Extends Cypress' cy commands with localStorage methods. Allows preserving localStorage between tests and spec files. Allows disabling localStorage.

License: MIT License

JavaScript 81.49% HTML 0.56% CSS 1.20% TypeScript 16.67% Shell 0.08%
cypress localstorage local-storage methods utilities commands testing-tools testing persistence cypress-plugin

cypress-localstorage-commands's Introduction

Build status Coverage Status Quality Gate Mutation testing status

Renovate Last commit Last release

NPM downloads License

Cypress localStorage commands

Extends Cypress' cy commands with localStorage methods. Allows preserving localStorage between tests and spec files, and disabling localStorage.

The problems

  • You want to preserve localStorage between Cypress tests.
  • You want to preserve localStorage between Cypress spec files.
  • You want to disable localStorage to check error handling.

This solution

This solution allows you to use all browser localStorage methods through Cypress commands, and preserve it between tests and spec files. It also allows to simulate that localStorage is disabled in the browser.

Alternatives

As from Cypress 12, you can use cy.session and Cypress Test Isolation in order to persist localStorage between tests. Anyway, this plugin can be still used for an easier manipulation of the localStorage, writing localStorage assertions and even disabling it for checking the error handling.

Installation

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

Installing commands

cypress-localstorage-commands extends Cypress' cy commands.

At the top of your Cypress' support file (usually cypress/support/e2e.js for e2e testing type):

import "cypress-localstorage-commands";

Read Cypress configuration docs for further info.

Installing commands in Cypress <10.0

Add this line to your project's cypress/support/index.js:

import "cypress-localstorage-commands"

Installing Node events

⚠ In order to support preserving localStorage across Cypress spec files, the plugin's Node events must be installed also. Otherwise, localStorage will be preserved only across tests in the same spec file.

In the cypress.config.js file:

module.exports = {
  e2e: {
    setupNodeEvents(on, config) {
      require("cypress-localstorage-commands/plugin")(on, config);
      return config;
    },
  },
};
Installing Node events in Cypress <10.0

In the cypress/plugins/index.js file:

module.exports = (on, config) => {
  require("cypress-localstorage-commands/plugin")(on, config);
  return config;
};

Usage

Commands

cy.saveLocalStorage([snapshotName])

Saves current localStorage values into an internal "snapshot".

  • snapshotName (String): Optionally, a snapshotName can be provided, and then data from localStorage will be saved into a snapshot with that name. So, multiple snapshots can be stored.

cy.restoreLocalStorage([snapshotName])

Restores localStorage to previously "snapshot" saved values. __

  • snapshotName (String): Optional. If provided, the localStorage will be restored using data from that specific snapshot.

cy.clearLocalStorageSnapshot([snapshotName])

Clears localStorage "snapshot" values, so previously saved values are cleaned.

  • snapshotName (String): Optional. If provided, only data from that specific snapshot will be cleared.

cy.getLocalStorage(item)

Gets localStorage item. Equivalent to localStorage.getItem in browser.

  • item (String): Item to get from localStorage.

cy.setLocalStorage(item, value)

Sets localStorage item. Equivalent to localStorage.setItem in browser.

  • item (String): Item to set value.
  • value (String): Value to be set.

cy.removeLocalStorage(item)

Removes localStorage item. Equivalent to localStorage.removeItem in browser.

  • item (String): Item to be removed.

cy.disableLocalStorage(options)

Disables localStorage. It produces localStorage methods to throw errors.

  • options (Object): Options to use when disabling localStorage.
    • withError (Error): If provided, invocations to localStorage methods will throw this error.

Preserving local storage between tests

Use cy.saveLocalStorage() to save a snapshot of current localStorage at the end of one test, and use the cy.restoreLocalStorage() command to restore it at the beginning of another one. The usage of beforeEach and afterEach is recommended for this purpose.

⚠ When the plugin's Node events are installed, the cy.restoreLocalStorage() command will be able to restore the localStorage snapshots saved in other spec files. Otherwise, snapshots are completely cleared between spec files.

Examples

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)

describe("Accept cookies button", () => {
  const COOKIES_BUTTON = "#accept-cookies";

  before(() => {
    cy.clearLocalStorageSnapshot();
  });

  beforeEach(() => {
    cy.restoreLocalStorage();
    cy.visit("/");
  });

  afterEach(() => {
    cy.saveLocalStorage();
  });

  it("should be visible", () => {
    cy.get(COOKIES_BUTTON).should("be.visible");
  });

  it("should not be visible after clicked", () => {
    cy.get(COOKIES_BUTTON).click();
    cy.get(COOKIES_BUTTON).should("not.be.visible");
  });

  it("should not be visible after reloading", () => {
    cy.get(COOKIES_BUTTON).should("not.be.visible");
  });
});

Note the usage of beforeEach and afterEach for preserving localStorage between all tests. Also cy.clearLocalStorageSnapshot is used in the before statement to avoid possible conflicts with other spec files preserving localStorage.

localStorage assertions

Based on the previous example, assertions could be added to check values of localStorage:

describe("localStorage cookies-accepted item", () => {
  beforeEach(() => {
    cy.restoreLocalStorage();
    cy.visit("/");
  });

  afterEach(() => {
    cy.saveLocalStorage();
  });

  it("should be null first time page is visited", () => {
    cy.getLocalStorage("cookies-accepted").should("equal", null);
  });

  it("should be true after clicking cookies button", () => {
    cy.get("#accept-cookies").click();
    cy.getLocalStorage("cookies-accepted").should("equal", "true");
  });

  it("should be true after reloading", () => {
    cy.getLocalStorage("cookies-accepted").then(cookiesAccepted => {
      expect(cookiesAccepted).to.equal("true");
    });
  });
});

Named snapshots

Next example shows how named snapshots can be used to storage different states of localStorage and restore one or another depending of the test:

describe("Accept cookies button", () => {
  const COOKIES_BUTTON = "#accept-cookies";

  before(() => {
    cy.clearLocalStorageSnapshot();
  });

  it("should be visible", () => {
    cy.visit("/");
    cy.get(COOKIES_BUTTON).should("be.visible");
    cy.saveLocalStorage("cookies-not-accepted");
  });

  it("should not exist after clicked", () => {
    cy.get(COOKIES_BUTTON).click();
    cy.get(COOKIES_BUTTON).should("not.exist");
    cy.saveLocalStorage("cookies-accepted");
  });

  it("should be visible when cookies are not accepted", () => {
    cy.restoreLocalStorage("cookies-not-accepted");
    cy.visit("/");
    cy.get(COOKIES_BUTTON).should("be.visible");
  });

  it("should not exist when cookies are accepted", () => {
    cy.restoreLocalStorage("cookies-accepted");
    cy.visit("/");
    cy.get(COOKIES_BUTTON).should("not.exist");
  });
});

Disabling localStorage

Use cy.disableLocalStorage() to simulate that localStorage is disabled, producing that any invocation to localStorage.setItem, localStorage.getItem, localStorage.removeItem or localStorage.clear will throw an error. As MDN docs recommend, "developers should make sure to always catch possible exceptions from setItem()". This command allows to test that possible exceptions are handled correctly.

Note that:

  • Only pages loaded after calling this command will have localStorage disabled, so always use cy.reload or cy.visit after executing it.
  • The localStorage only remains disabled for all pages loaded during the current test. If you want to disable it for multiple tests, execute it in all of them, or in a beforeEach statement.
  • If any of the other plugin commands (except clearLocalStorageSnapshot) is executed while localStorage is disabled, it will do nothing but producing a Cypress log as: "localStorage.setItem is disabled"

Examples

Disabling localStorage in a single test

Based on previous "Accept cookies button" example, next tests could be added:

//...
const LOCALSTORAGE_DISABLED_WARNING = "#localstorage-disabled-warning";
const LOCALSTORAGE_ERROR = "#localstorage-error";

//... should not be visible after clicked

it("should still be visible when reloading if localStorage is disabled", () => {
  cy.disableLocalStorage();
  cy.reload();
  cy.get(COOKIES_BUTTON).should("be.visible");
});

it("should display warning if localStorage is disabled", () => {
  cy.disableLocalStorage();
  cy.reload();
  cy.get(LOCALSTORAGE_DISABLED_WARNING).should("be.visible");
});

it("should display localStorage error message", () => {
  cy.disableLocalStorage();
  cy.reload();
  cy.get(LOCALSTORAGE_ERROR).should("have.text", "Error");
});

// ...should not be visible after reloading

Disabling localStorage in multiple tests

describe("when localStorage is disabled", () => {
  beforeEach(() => {
    cy.disableLocalStorage({
      withError: new Error("Disabled by cypress-localstorage-commands"),
    });
    cy.visit("/");
  });

  it("should display localStorage warning", () => {
    cy.get("#localstorage-disabled-warning").should("be.visible");
  });

  it("should display localStorage error message", () => {
    cy.get("#localstorage-error").should("have.text", "Disabled by cypress-localstorage-commands");
  });

  it("should display accept-cookies button disabled", () => {
    cy.get("#accept-cookies").should("be.disabled");
  });
});

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 tsconfig.json file:

{
  "compilerOptions": {
    "types": ["cypress", "cypress-localstorage-commands"]
  }
}

Or reference the package in the files using it:

/// <reference types="cypress-localstorage-commands" />

Contributing

Contributors are welcome. Please read the contributing guidelines and code of conduct.

License

MIT, see LICENSE for details.

cypress-localstorage-commands's People

Contributors

fossabot avatar greenkeeper[bot] avatar javierbrea avatar jmyfromads avatar renovate-bot avatar renovate[bot] avatar vitaliytv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cypress-localstorage-commands's Issues

Problem saving local storage in Chrome browser

Describe the bug
Hello, I installed this plugin because it fits exactly with what I wanted to do, but I'm having some problems in Chrome. I have multiple forms on different pages, the responses of which we save into an object in local storage until the final form where the user submits the form, and the object in local storage gets sent to an API.
I'm testing to see whether this object is correct when I send it to the API, which requires me to persist local storage so that I can access the final object. During the test run it persists as expected, but at some point, local storage is inexplicably cleared, then starts persisting again!
I already have the chromeWebSecurity set to false.
This seems to work with electron in headless mode.

Expected behavior
To work correctly in Chrome browser

edit:
Versions
Cypress 4.12.1
cypress-localstorage-commands 1.2.2
Chrome 86

I added a log so I can see in the cypress UI when they get execute

Cypress.Commands.add('clearLS', () => {
  cy.log('Clear Local Storage');
  cy.clearLocalStorageSnapshot();
});

Cypress.Commands.add('restoreLS', () => {
  cy.log('Restore Local Storage');
  cy.restoreLocalStorage();
});

Cypress.Commands.add('SaveLS', () => {
  cy.log('Save Local Storage');
  cy.saveLocalStorage()
});

I added the commands on my base test so i can use it n more than one script without calling it all the time

BaseTest.PreservingLocalStorage = function(testSuite) {
  describe('Preserving Local Storage', function() {
    before(function() {
      cy.clearLS();
    });

    beforeEach(function() {
      cy.restoreLS()
    });

    afterEach(function() {
      cy.SaveLS();
    });
    
    testSuite();
  });
}

This is an example on how the test look it has more "it" than this example

BaseTest.PreservingLocalStorage(function() {
  describe('Test of pages', function() {
    it('Select option 1', function() {
      SelectoptionFirstPage
        .VisitTheLanding(url)
        .ClickOnOption(1);
    });

    it('Select Option 2', function() {
        SelectOptionSecondPage
          .ClickOnOption(2);
    });

    it('Select Option 2', function() {
        SelectOptionThirdPage
          .ClickOnOption(3);
    });
  });
});

Synchronized function invoke

Is your feature request related to a problem? Please describe.
The restore and save storage is async function like other cypress functions.

In our case, we need to check a certain token in before() function of each spec. If it is valid then we can skip some certain steps. Such as login etc.

So, we need to restore the storage and check the token in the storage and then invoke certain functions based on the result of last step.

  • I had tried to use async / await to make the function work as sync function. But Cypress did not allow this kind of operations. Failed with exceptions.
  • I had chained all the operations with .then() in before() hook within each spec. But it failed with exceptions as well.

It said that cypress already make all function return a promise and cypress will determine the exec order.

So, I wonder if it is possible to make a synchronized function. Or maybe it is impossible to achieve this goal at all. If that is impossible, I shall drop this idea. The tests work well currently, I just want to improve the performance by skip some steps. Thank you!

Additional context
E.g. I have two specs.
A.spec:
before('1. login', () => {
cy.restoreLocalStorage()
const token = cy.getLocalStorage('testToken')
// decode token
if (token.exp <= Date.current() / 1000) {
cy.login('userA')
}
})
after(() => {
cy.saveLocalStorage()
})
B.spec:
before('1. login', () => {
cy.restoreLocalStorage()
const token = cy.getLocalStorage('testToken')
// decode token
if (token.exp <= Date.current() / 1000) {
cy.login('userA')
}
})
after(() => {
cy.saveLocalStorage()
})

Cypress 8 compatibility

Describe the bug
Cannot install cypress 8 and cypress-localstorage-commands together

To Reproduce
Try installing cypress 8 and cypress-localstorage-commands

Expected behavior
Should work with cypress 8

Logs
When trying to update cypress 7 to 8:

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! Found: [email protected]
npm ERR! node_modules/cypress
npm ERR!   dev cypress@"^8.0.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer cypress@"^2.1.0 || 3.x || 4.x || 5.x || 6.x || 7.x" from [email protected]
npm ERR! node_modules/cypress-localstorage-commands
npm ERR!   dev cypress-localstorage-commands@"^1.4.5" from the root project

Operating system, Node.js an npm versions, or browser version (please complete the following information):

  • OS: Windows 10
  • Node.js: v16.2.0
  • npm: 7.13.0

Additional context
It's probably sufficient to add 8.x to the allowed versions of the cypress peer dependency.

Running tests against remote: `Permission denied to access property "document" on cross-origin object`

Describe the bug (This might not be a bug, can also be configuration)
I love this tool. Now I try to run my tests on multiple environments.
Currently I have local and dev.

Locally I am using http://localhost:3000 as baseUrl.
Remotely I use https://my-own-aws-amplify-app.com.

Before every test I clear or persist local storage (view below).
Everything works fine locally.

But on the remote I get the error: Permission denied to access property "document" on cross-origin objectwhen trying to clearLocalStorage.

To Reproduce
Here is the logic I run before and after (every) test in my module.

  before(() => {
    cy.clearLocalStorage();
  });

  beforeEach(() => {
    cy.loginAndSaveSession();
  });

  after(() => {
    cy.clearLocalStorage();
  });

loginAndSaveSession authenticates with an existing userpool and saves set the credentials in localStorage.

Expected behavior
A clear and concise description of what you expected to happen.

Logs

SecurityError: Permission denied to access property "document" on cross-origin object
    setWindowDocumentProps@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:169343:3
    initialize/<@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:170126:33
    dispatch@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:91191:27
    add/elemData.handle@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:90999:28
From previous event:
    run@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:169809:21
    addCommand/cy[name]@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:170266:11
    ./cypress/integration/auth.spec.js/</<@https://my-own-aws-amplify-app.com/__cypress/tests?p=cypress/integration/auth.spec.js:118:8
    setRunnable/runnable.fn@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:170493:45
    callFn@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:104252:21
    onRunnableRun/<@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:176051:28
From previous event:
    onRunnableRun@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:176039:10
    action@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:166634:28
    patchRunnableRun/Runnable.prototype.run@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:174418:13
    next/<@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:105037:12
    next@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:104820:14
    next/<@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:104830:11
    next@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:104732:14
    next/<@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:104793:11
    next@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:175972:22
    onNext/<@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:175994:15
From previous event:
    onNext@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:175991:57
    done@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:104192:7
    callFn/<@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:104257:11
From previous event:
    callFn@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:104255:14
    onRunnableRun/<@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:176051:28
From previous event:
    onRunnableRun@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:176039:10
    action@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:166634:28
    patchRunnableRun/Runnable.prototype.run@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:174418:13
    next@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:104754:10
    timeslice@https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:98724:27 cypress_runner.js:200069:13
    logError https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:200069
    addGlobalListeners https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:199724
    emit https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:51573
    listen https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:184805
    emit https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:51573
    emit https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:184845
    onPrint https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:183754
    _onPrintClick https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:183759
    initializer https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:185016
    executeAction https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:49438
    n https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:49438
    ca https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:59970
    ja https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:59971
    ka https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:59971
    wa https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:59973
    Aa https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:59974
    ya https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:59974
    Da https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:59977
    Ad https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:60040
    Gi https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:60206
    Kb https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:59995
    Dd https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:60042
    Ii https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:60207
    unstable_runWithPriority https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:64081
    Ii https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:60207
    Cd https://my-own-aws-amplify-app.com/__cypress/runner/cypress_runner.js:60041

** Operating system, Node.js an npm versions, or browser version (please complete the following information):**

  • OS: [mac]
  • Node.js: [12.20.1]
  • cypress-localstorage-commands: [1.4.0]
  • Browser: [Firefox 84]

What is causing the problem Permission denied to access property "document" on cross-origin object ?

clearLocalStorage()

Is your feature request related to a problem? Please describe.
It's good to reset things before starting, especially when not working with a fresh instance of the product.

Describe the solution you'd like
A new function/method.

Node 10.x support?

Is your feature request related to a problem? Please describe.
I am facing the following error when deploying with AWS CodePipeline:
error [email protected]: The engine "node" is incompatible with this module. Expected version "12.x || 13.x || 14.x || 15.x". Got "10.1.0"

Describe the solution you'd like
Is this package compatible with node 10.x at all?

Describe alternatives you've considered
Obviously upgrading node, but I'm just curious if 10.x could be supported?

cypress-localstorage import

Hello, just a quick note as i'm new to Cypress and this plugin. If you add Cypress to an Angular 2+ project it comes automatically with typescript. Cypress don't recognise your plugin if the import "cypress-localstorage-commands" is in cypress/support/command.ts, you're stuck with errors like cy.clearLocalStorageSnapshot is not a function.. Instead of having the import in cypress/support/command.ts, it should be in cypress/support/index.ts.

File structure :
image

cypress/support/index.ts.
image

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • chore(deps): update endbug/version-check action to v2.1.4

Rate-Limited

These updates are currently rate-limited. Click on a checkbox below to force their creation now.

  • chore(deps): update dependency eslint to v8.57.0
  • chore(deps): update dependency eslint-plugin-jest to v27.9.0
  • chore(deps): update dependency eslint to v9
  • chore(deps): update dependency eslint-plugin-jest to v28
  • fix(deps): update dependency react-redux to v9
  • fix(deps): update dependency redux to v5
  • 🔐 Create all rate-limited PRs at once 🔐

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/build.yml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/cache v4
  • actions/upload-artifact v4
  • actions/upload-artifact v4
  • actions/upload-artifact v4
  • actions/checkout v4
  • actions/download-artifact v4
.github/workflows/check-package-version.yml
  • actions/checkout v4
  • EndBug/version-check v2.1.1
  • martinbeentjes/npm-get-version-action v1.3.1
  • mindsers/changelog-reader-action v2.2.2
  • christian-draeger/read-properties 1.1.1
.github/workflows/publish-to-github.yml
  • actions/checkout v4
  • actions/setup-node v4
  • MerthinTechnologies/edit-json-action v1
.github/workflows/publish-to-npm.yml
  • actions/checkout v4
  • actions/setup-node v4
npm
package.json
  • @babel/eslint-parser 7.24.5
  • @babel/preset-react 7.24.1
  • @stryker-mutator/core 8.2.6
  • @stryker-mutator/jest-runner 8.2.6
  • cypress 13.9.0
  • eslint 8.53.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-jest 27.6.0
  • eslint-plugin-mocha 10.4.3
  • eslint-plugin-no-only-tests 3.1.0
  • eslint-plugin-prettier 5.1.3
  • eslint-plugin-react 7.34.1
  • husky 9.0.11
  • is-ci 3.0.1
  • jest 29.7.0
  • lint-staged 15.2.2
  • prettier 3.2.5
  • sinon 18.0.0
  • typescript 5.4.5
  • cypress >=2.1.0
  • node >=14.0.0
test-e2e/app/package.json
  • @data-provider/browser-storage 4.0.0
  • @data-provider/core 4.0.0
  • @data-provider/react 2.0.0
  • prop-types 15.8.1
  • react 18.3.1
  • react-dom 18.3.1
  • react-redux 8.1.3
  • redux 4.2.1
  • babel-plugin-module-resolver 5.0.2
  • react-scripts 5.0.1
  • serve 14.2.3
test-e2e/cypress-9-no-plugin/package.json
  • @cypress/webpack-preprocessor 6.0.1
  • babel-loader 9.1.3
  • babel-plugin-module-resolver 5.0.2
  • cypress 9.7.0
  • start-server-and-test 2.0.3
  • webpack 5.91.0
test-e2e/cypress-9/package.json
  • @cypress/webpack-preprocessor 6.0.1
  • babel-loader 9.1.3
  • babel-plugin-module-resolver 5.0.2
  • cypress 9.7.0
  • start-server-and-test 2.0.3
  • webpack 5.91.0
test-e2e/cypress-latest-no-plugin/package.json
  • @cypress/webpack-preprocessor 6.0.1
  • babel-loader 9.1.3
  • babel-plugin-module-resolver 5.0.2
  • cypress 13.9.0
  • start-server-and-test 2.0.3
  • webpack 5.91.0
test-e2e/cypress-latest/package.json
  • @cypress/webpack-preprocessor 6.0.1
  • babel-loader 9.1.3
  • babel-plugin-module-resolver 5.0.2
  • cypress 13.9.0
  • start-server-and-test 2.0.3
  • webpack 5.91.0
test-e2e/cypress-typescript/package.json
  • @typescript-eslint/eslint-plugin 7.9.0
  • @typescript-eslint/parser 7.9.0
  • cypress 13.9.0
  • eslint 8.56.0
  • eslint-config-prettier 9.1.0
  • eslint-plugin-prettier 5.1.3
  • start-server-and-test 2.0.3
  • typescript 5.4.5

  • Check this box to trigger a request for Renovate to run again on this repository

Support for cypress 9.x

I get an error when I want to use v1.6.0 with cypress v9.0.0:

 Could not resolve dependency:
npm ERR! peer cypress@"^2.1.0 || 3.x || 4.x || 5.x || 6.x || 7.x || 8.x" from [email protected]

Use of mutation testing in cypress-localstorage-commands - Help needed

Hello there!

My name is Ana. I noted that you use the mutation testing tool strykerjs in the project.
I am a postdoctoral researcher at the University of Seville (Spain), and my colleagues and I are studying how mutation testing tools are used in practice. With this aim in mind, we have analysed over 3,500 public GitHub repositories using mutation testing tools, including yours! This work has recently been published in a journal paper available at https://link.springer.com/content/pdf/10.1007/s10664-022-10177-8.pdf.

To complete this study, we are asking for your help to understand better how mutation testing is used in practice, please! We would be extremely grateful if you could contribute to this study by answering a brief survey of 21 simple questions (no more than 6 minutes). This is the link to the questionnaire https://forms.gle/FvXNrimWAsJYC1zB9.

Drop me an e-mail if you have any questions or comments ([email protected]). Thank you very much in advance!!

restoreLocalStorage doesn't wait for restore to complete

Describe the bug

There seems to be a delay between calling cy.restoreLocalStorage() and when the local storage values are fully restored.

We are having to put a cy.wait() after the restore to get around this issue which is not ideal. Shouldn't cy.restoreLocalStorage() wait for the restore to be complete before returning?

restoreLocalStorage do not works

Hello
I'm facing an issue with local storage for login
I would like to stay logged between each it

/// <reference types="Cypress" />

describe('Open Main Screens', () => {
  before(() => {
    cy.clearLocalStorageSnapshot()
    cy.myLogin('abc', 'def') // login with UI
    cy.saveLocalStorage() // should save the current local storage that contains JWT variable
  })

  beforeEach(() => {
    cy.restoreLocalStorage() // should restore local storage and JWT variable 
  })

  it('open reports page', function () {
// I see in local storage JWT variable is not here 
  })

I check the local storage in the opened chrome for tests

After login, I saw AuthToken
And in the it, AuthToken is not present despite cy.restoreLocalStorage() in beforeEach

Is it a bug ? or I do not use well this lib ?

Ubuntu 21.10
Last version of node and npm
Last version of Cypress : 9.5.2
Last version of localstorage plugin : 1.7.0

Thank you

Working with Cypress CLI

Hello @javierbrea

Thank you for this really useful plugin.
Just would like to know, does this work when running tests in cypress CLI mode ? I observed its failing to preserve the local storage when test runs in cli headless mode

Thanks & Warm Regards,

import 'cypress-localstorage-commands' makes problems in Angular project with jasmine

Your library is very helpful for our cypress tests.

We had a problem that when we put import 'cypress-localstorage-commands' into our commands.ts file the jasmine expect has now the chai typing and so there is no intelliSense for the jasmine syntax any more.

I solved it with the following:
Do not put import 'cypress-localstorage-commands' into your commands.ts file but put the type cypress-localstorage-commands in your cypress/tsconfig.json like this:

"types": ["cypress", "cypress-localstorage-commands"]

@javierbrea Maybe you want to add this to your ReadMe.

Support Cypress v6.x

It is desirable to add Cypress v6.x to the list of supported Cypress versions once the plugins tests have been fixed. There is already a PR opened by @renovate-bot (#194 ), but the build is broken because tests are failing. It is probably related to a breaking change in the new Cypress version about asserting elements that do not exist on the DOM (https://docs.cypress.io/guides/references/changelog.html#6-0-0 -> "Cypress now always throws an error when asserting on an element that doesn’t exist in the DOM")

It is needed to change that E2E tests to adapt them to the new Cypress version and update the package.json file to indicate that the plugin supports it.

Typescript support

Hello,
Is there any intentions to add typescript support for this library?
Or if there is already a way can you point it out?

Feature: Disable local storage

Is your feature request related to a problem? Please describe.

When working with localStorage it's almost always necessary to handle exceptions as well. IT would be useful if this plugin would offer a way to easily disable the local storage.

Describe the solution you'd like

Maybe cy.disableLocalStorage() and cy.enableLocalStorage() commands, for example.

Describe alternatives you've considered

Don't actually know any easy alternative at the moment (hence the ticket).

Additional context

I really like this plugin, Thank You for your work 👍

With dynamic test, `getLocalStorage` on `after` hooks return undefined

Describe the bug

I have a situation where I need to set localStorage with cy.setLocalStorage() inside Cypress before hook, and run some dynamic test, and on after hook I want to get the final data from localStorage back, but turns out, runing cy.getLocalStorage() on Cypress's after hook will result in an undefined data

To Reproduce

I have compiled down into minimum reproducible test, here is the code:

// test.cy.js
import "cypress-localstorage-commands";

describe("Minimum repro", () => {
  before(() => {
    cy.setLocalStorage("foo", JSON.stringify({ state: "completed" }));
  });

  after(() => {
    cy.getLocalStorage("foo").then((data) => {
      // data will be undefined
      // since writeFile require the second argument to exist, it will throw
      cy.writeFile("cypress/path/to/foo.json", data);
    });
  });

  // Test section
  [1, 2].forEach((_, index) => {
    it(`Dynamic ${index + 1}`, () => expect(true).equal(true));
  });
});

If you run that you will have an error (you can see the screenshot in the logs) because data is undefined.
However, when I tried to get rid of the forEach and swap the // Test section with normal test like this code below, it works fine

// snip ...
  it("Static", () => expect(true).equal(true));
// snip ...

I was curious, I tried to move the getLocalStorage command inside the // Test section and remove the after hooks, if I set to run the command at the very first index, it works, otherwise it doesn't work, here's the full code

import "cypress-localstorage-commands";

describe("Minimum repro", () => {
  before(() => {
    cy.setLocalStorage("foo", JSON.stringify({ state: "completed" }));
  });

  [1, 2, 3].forEach((_, index) => {
    it(`Dynamic ${index + 1}`, () => {
      if (index === 0) { // if you change this to 1 or 2, it doesn't work, and data below will not exist
        cy.getLocalStorage("foo").then((data) => {
          // data is exist
          cy.writeFile("cypress/path/to/foo.json", data);
        });
      }

      expect(true).equal(true);
    });
  });
});

Expected behavior

with dynamic test script, cy.getLocalStorage should return the exact data instead of undefined

Logs

image

Thank you!

Improve documentation examples

Currently documentation does not show how to use properly the localStorage commands in a Cypress beforeEach statement.

It is desirable also to add an example showing how to make an assertion based on current localStorage value using the cy.getLocalStorage command.

getLocalStorage(key).then(value) TypeScript error

Describe the bug

/// <reference types="cypress-localstorage-commands" />

export const getLocalStorage = (key: string): any =>
  cy.getLocalStorage(key).then(value => {
    if (value === null) {
      return value;
    } else {
      return JSON.parse(value);
    }
  });
error TS2345: Argument of type 'Element' is not assignable to parameter of type 'string'.

Expected behavior
value should be string | null.

Logs
If applicable, add logs to help explain your problem.

Operating system, Node.js an npm versions, or browser version (please complete the following information):

  • OS: macOS 10.15.4
  • Node.js: 12.16.3
  • npm: 6.14.4

cypress-localstorage-commands breaks Jest typings

Describe the bug
So we're using cypress-localstorage-commands in our Angular 2 (9.1.0) project. We're using Jest for unit testing, and cypress-localstorage-commands seems to break the typings that Jest uses.

image

I have a separate tsconfig for cypress tests and for unit tests. For cypress the path is project-root/cypress/tsconfig.json. Path for unit tests tsconfig is project-root/src/tsconfig.spec.json.

I have imported cypress-localstorage-commands in project-root/cypress/support/index.ts. As soon as I remove the import row, the error above disappears:
image

When I add the import row back, it appears again.

We're using TypeScript with Cypress as well.

To Reproduce
Import cypress-localstorage-commands as documented in a TypeScript project which uses Jest, and Cypress with Typescript.

Expected behavior
It should use Jest typings.

** Operating system, Node.js an npm versions, or browser version (please complete the following information):**

  • OS: Windows 10
  • Node.js: 12.13.1
  • npm: 6.12.1

Improve commands documentation

It is desirable to improve commands documentation. Currently the description of each command is a comment in the code example, maybe it is better to describe the api of each command before the example.

Add acceptance tests

It is desirable to add acceptance tests. Tests should consist in really starting a cypress instance testing an application which uses localStorage.

Convert into monorepo

From version 2.2 the E2E tests are being executed with many different Cypress versions and configurations. This was made extracting the common Cypress spec files and the application used to run tests to a separated folder, and creating one different E2E folder for each different Cypress version/configuration.

This produced to have many dependencies duplicated on each different Cypress folder, and to repeat some tasks during the execution of different E2E tests, such as the build of the app, etc.

It is desirable to convert the project structure into a monorepo in order to take advantage of monorepo tools such as the tasks orchestration. So, it will be easier and faster to run tests locally as well as in pipelines.

Using a monorepo tool in the project would make very easy to move the core library logic to a new library, allowing to publish a new plugin for managing the sessionStorage by reusing it. #254

Node 16 is incompatible

Describe the bug
Latest release (1.4.3) is not compatible with Node 16

To Reproduce

  • use Node >= 16
  • try to install the library

Expected behavior
The lib should install correctly on Node >= 16

Logs
While installing the lib (yarn add -D cypress-localstorage-commands), following log appears:

error [email protected]: The engine "node" is incompatible with this module. Expected version "10.x || 12.x || 14.x || 15.x". Got "16.0.0"
error Found incompatible module.

** Operating system, Node.js an npm versions, or browser version (please complete the following information):**

  • OS: Debian 11
  • Node.js: v16.0.0
  • npm: 7.10.0
  • Browser: n/a

Update Cypress 7.* to peerDependencies

Is your feature request related to a problem? Please describe.
Hardcoded dependencies need to have 7.* added.

Describe the solution you'd like
Update peerDependency

Describe alternatives you've considered
n/a

Additional context
n/a

LocalStorage missing across spec files

. I installed this plugin using npm i --save-dev cypress-localstorage-commands

. And I added this line: import "cypress-localstorage-commands" into cypress/support/commands.js

. In my testcase.ts file, I added

image

And when I execute, it does not store cookies

image

Cypress 12 Compatibility

Greetings from the @cypress-io team. Cypress 12 is coming out next week, and some changes might affect your plugin. One of the big changes is introducing a new API to register custom commands, which helps fix one of the oldest and most annoying issues with Cypress, the “Detached DOM” error.

For commands that are classified as queries (mainly used to return something like a DOM element), there is a new Cypress.Commands.addQuery method. The addQuery method greatly simplifies writing custom query commands and has the benefit of not encountering detached DOM errors.

If your plugin currently registers custom command “queries”, we recommend updating your plugin to use the new API for Cypress 12. Note the API is only going to be in Cypress 12 and newer.

To test out a prerelease version of Cypress 12, you can follow the instructions for installing a prerelease binary here, but instead of using the develop branch use the release/12.0.0 branch.

We recommend all plugin authors test their plugins against the Cypress 12 prerelease to check for compatibility.

If you have any questions, contact us by pinging me on this issue or in our Discord server.

You might find our Retry-ability Guide (updated to cover the latest changes), and Cypress 12 Migration Guide | Cypress Documentation helpful as well.

Thanks

SessionStorage

Is your feature request related to a problem? Please describe.
When testing an application that stores session details in Session Storage instead of Local Storage, it would be good to use the same utilities provided by this library. Since SessionStorage is exactly the same as LocalStorage except for when it's cleared, this should be a very similar implementation.

Describe the solution you'd like
Same methods provided except for SessionStorage

Describe alternatives you've considered
None

Additional context
None

Pass snapshot name to save/restore

I think it could be useful to pass a snapshot argument to the saveLocalStorage method. For example, I have a case where I need to preserve my login data from localStorage between tests, since Cypress clears it by default. With this proposal, you can do:

function loginCommand() {
  // ...
  cy.saveLocalStorage('login')
}

And then in my support/index.js:

beforeEach(() => {
  cy.restoreLocalStorage('login')
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.