Is it possible to combine beforeEach & afterEach Cypress's hooks into a custom command?

Viewed 400

Is it possible to combine a custom command which gets trigger in both beforeEach & afterEach hooks? I'm currently using the cypress-localstorage-commands plugin like so:

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

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

Is there a way to abstract this into a custom command so I don't need to add these hooks or reuse this code in each spec file?

1 Answers

I'm not an expert in Cypress specifically, but all testing libraries have to play by the rules of Javascript: their "special functions" (like beforeEach/afterEach) are still just Javascript functions.

Thus, I believe that if you want to make a function that adds both a beforeEach and afterEach, it should be as simple as:

const addBoth = () => {
    beforeEach(() => {
      cy.restoreLocalStorage();
    });

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

and then you just call:

addBoth();

everywhere that you want to add both. And this should be true of any JS library (testing or otherwise), unless it is doing something really clever involving function scopes behind the scenes (eg. React hooks).

Related