Skip to content

Instantly share code, notes, and snippets.

@sorenlouv
Last active September 1, 2022 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sorenlouv/4dfe62d30481ee3cd73010794badf2e0 to your computer and use it in GitHub Desktop.
Save sorenlouv/4dfe62d30481ee3cd73010794badf2e0 to your computer and use it in GitHub Desktop.
Cypress tips and tricks

Don't await Cypress methods

Given this backend task:

// plugins.ts
const plugin: Cypress.PluginConfig = (on, config) => {
  on('task', {
    async waitForMe(ms: number) {
      return new Promise((resolve) => {
        setTimeout(() => resolve(null), ms);
      });
    }
  }
};

WRONG

Intuitively an async task should be await'ed.

// feature.spec.ts
beforeEach(async () => {
  await cy.task('waitForMe');
});

CORRECT

However, the correct approach is to simply call it and let Cypress queue the task

// feature.spec.ts
beforeEach(() => {
  cy.task('waitForMe');
});

See Cypress Docs for details

Setup intercepts before opening the page

It is important that interceptors are setup before opening the page that fires the requests that are intercepted. If the interceptors are setup after the requests were made, they will not be captured and the test will timeout during cy.wait,

WRONG

it('calls the dependencies API', () => {
  cy.visit('/app/apm/services');
  cy.intercept('GET', '/internal/apm/dependencies/top').as('topDependencies');
  cy.wait('@topDependencies');
});

Correct

it('calls the dependencies API', () => {
  cy.intercept('GET', '/internal/apm/dependencies/top').as('topDependencies');
  cy.visit('/app/apm/services');
  cy.wait('@topDependencies');
});

Prefer cy.visitKibana instead of cy.visit

In most cases we should use cy.visitKibana instead of cy.visit. cy.visitKibana will wait for Kibana to have successfully loaded before moving on. This will reduce the risk of timing out later in the test because we split up the wait time in two parts: Kibana load time, and APM load time thus a time budget for each (by default 40 seconds).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment