Cypress adding context to failed tests

Viewed 98

I would like to add some context on each fail by getting some localstorage data and log that.. but not really sure how I can do it

In index.ts I added

Cypress.on('fail', (error, runnable) => {})

and there I do const user = localStorage.getItem('user'); and try to log it but now luck.. guess that I need to fetch it async but not able to get it to work :/

2 Answers

Use the synchronous version of .log().

I guess the queue stops running before the fail event is captured.

Cypress.on('fail', (error, runnable) => {
  const user = localStorage.getItem('user')
  Cypress.log({name: 'User', message: user})
})

it('', () => {
  localStorage.setItem('user', 'my-user')
  expect(1).to.eq(2)
})

I actually got it working by doing this in my support/index.ts file...

Cypress.on('fail', (error) => {
  const asyncLocalStorage = {
    getItem(key) {
      return Promise.resolve().then(function () {
        return localStorage.getItem(key);
      });
    },
  };

  asyncLocalStorage.getItem('state').then((localStorageState) => {
    const state = JSON.parse(localStorageState);

    Cypress.log({
      name: error.name,
      message: error.message,
      consoleProps: () => ({
        'User Id': state?.user?.id,
        members: state?.members,
        message: error.message,
        stack: error.stack,
      }),
    });
  });

  throw error;
});
Related