Skip to content

Instantly share code, notes, and snippets.

@the0neWhoKnocks
Last active May 30, 2021 18:28
Show Gist options
  • Save the0neWhoKnocks/330217972b423003427422c4a39aed9e to your computer and use it in GitHub Desktop.
Save the0neWhoKnocks/330217972b423003427422c4a39aed9e to your computer and use it in GitHub Desktop.
cypress notes

Cypress Notes


Create and use an alias for an element

cy.get('.item').as('ITEM');
cy.get('@ITEM').click();

Take screenshots

Somewhere in your test setup, either in a test file, or a setup file.

let screenshotNdx = 0;
const pad = (num, token='00') => token.substring(0, token.length-`${ num }`.length) + num;
function screenshot(name, selector) {
  screenshotNdx++;

  const filename = `${ pad(screenshotNdx) }__${ name.replace(/\s/g, '-') }`;

  if (selector) cy.get(selector).screenshot(filename);
  else cy.screenshot(filename);
}

Use the utility

// entire view
screenshot('page rendered');

// just a specific element
screenshot('button', '.custom-btn');

Proxy all image requests from a URL to a specific image

Inside of e2e/cypress/fixtures add the image 1x1.png.

cy.intercept('GET', 'https://domain.com/path/**', { fixture: '1x1.png' });

Check that an element has a specific attribute

cy.get('@ALIAS').invoke('attr', 'data-title').should('equal', 'title text');

Check for specific text within a child element

cy.get('@ALIAS').find('.item').contains('expected text');

Wait for item to appear, and verify it's empty

cy.get('@ALIAS', { timeout: 10000 }).should('be.empty');

Click an item and verify something exists because of that click

cy.get('@ALIAS').click();
cy.get('.new-item');

Verify multiple things for a retrieved element with jQuery and Chai

cy.get('@ALIAS').then(($item) => {
  const imgSrc = $item.find('img').attr('src');
  expect(imgSrc).to.not.equal('');
});

Wait for requests

The below demonstrates how to test a progressive load scenario.

cy.intercept('GET', '/api/v1/endpoint').as('API_REQ');
cy.get('.wrapper').scrollTo('bottom', { duration: 1500 });
cy.wait('@API_REQ');
cy.get('.wrapper').scrollTo('bottom', { duration: 1500 });
cy.wait('@API_REQ');
// verify number of items

Read data from an external file

let data;
cy.readFile('/path/to/file.json').then((jsonData) => {
  data = JSON.parse(jsonData);
});

Verify an external file was created

cy.readFile('/path/to/file.json');

Check for data in the page's URL

cy.location().its('search').should('include', 'sort=newest');

Run external command

cy.exec(`rm -f ${ E2E_FOLDER }/cypress/screenshots/renamer.test.js/*`, { log: true }).then(() => {
  console.log('[DELETED] screenshots');
});

Enter text into an input

Note that there are special tokens that execute before the text is typed.

token action
{selectall} Selects all text
cy.get('@INPUT').type('{selectall}some text');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment