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
Thank you!