Ivan Kirshin
Ivan Kirshin

Reputation: 73

Cypress tests passes with `cypress open`, but fails with `cypress run`

I wrote the e2e tests. They pass all the time if I start them with cypress open. But if I use this command: cypress run --browser chrome --headed --no-exit --spec 'tests/e2e/specs/Samples.ts. I get many different errors. These errors are not similar. Some of them I don't know how to fix. And the important fact: If I open developer tools and restart the tests, all tests will pass. The same for Chrome and firefox. I have tried using different versions of cypress but to no avail. I guess the error types are not important in my issue, but I will explain one of them. enter image description here After the 8th step, cypress reports that the page has loaded and redirects to the login page. This could mean that the localStorage with the token was accidentally cleared. If I open developer tools and restart the tests, all tests will pass. The test is very simple. Also, I use two custom functions.

describe('Samples', () => {
  beforeEach(() => {
    cy.login();
  });

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

  context('Create sample', () => {
    const SAMPLE_DATA = {
      name: 'Test',
      description: 'Description',
      compound: 'Compound1; Compound1',
    };

    afterEach(() => {
      cy.get('[data-test-id=btn-create]').click();
      cy.location('hash').should('match', /\/samples\/\d+$/);
      // archive
      cy.get('[data-test-id=btn-more-menu]').click();
      cy.get('[data-test-id=btn-archive]').click();
      cy.get('[data-test-id=btn-restore]');
    });

    it('should create sample without device', () => {
      cy.visit(urlPages.app.SAMPLES);
      cy.get('[data-test-id=btn-show-create-sample-modal]').click();
      cy.get('[data-test-id=input-name]').type(SAMPLE_DATA.name);
      cy.get('[data-test-id=input-description]').type(SAMPLE_DATA.description);
      cy.get('[data-test-id=input-compounds]').type(SAMPLE_DATA.compound);
    });
  });
})

Upvotes: 4

Views: 2778

Answers (1)

Mike Feltman
Mike Feltman

Reputation: 5176

Not sure if this will help, but according to the Cypress best practices (https://docs.cypress.io/guides/references/best-practices#Using-after-or-afterEach-hooks, afterEach should be used sparingly and you should perform any necessary cleanup in the beforeEach so you can ensure a clean environment before each test run.

Perhaps eliminating the afterEach and changing your beforeEach to the following will help:

 beforeEach(() => {
    cy.deleteAccount();
    cy.login();
  });

I also think that the 2nd afterEach may be more reliable if it were simply a function that you called explicitly at that end of each test.

Upvotes: 0

Related Questions