cypress-helper-getcy

A simple Cypress command for getting elements via `data-cy` attributes

Usage no npm install needed!

<script type="module">
  import cypressHelperGetcy from 'https://cdn.skypack.dev/cypress-helper-getcy';
</script>

README

cypress-helper-getcy

A simple Cypress command for getting elements via data-cy attributes.

npm version npm downloads

Inspiration

Why not just cy.get("[data-cy='submit']")?

Well, I like clean tests, and I found both the test code and logs to be rather ugly and harder to read when doing that. So I wanted something cleaner, and made this, which cleans up both the code and the log. 👍

Setup

1. Install

npm install --save-dev cypress-helper-getcy

2. Import

// E.g. in cypress/support/index.js
import 'cypress-helper-getcy';

Tagging your subjects

Plain HTML

<form data-cy="search">
  <input data-cy="search/input" />
  <button data-cy="search/button">Search</button>
</form>

React, with useCypressTag helper

import React from 'react';
import { useCypressTag } from 'cypress-helper-getcy';

export default function Search(): React.Element {
  const tag = useCypressTag('search');
  return (
    <form {...tag()}>
      <input {...tag('input')} />
      <button {...tag('button')}>Search</button>
    </form>
  );
}

Note: If you get a bunch of TS2403 errors from Typescript after importing useCypressTag into your application code, see this issue for a workaround.

Getting your subjects

Plain

it('finds my tagged subjects', () => {
  cy.getCy('search').should('be.visible');
  cy.getCy('search/input').type('term');
  cy.getCy('search/button').click();

  cy.getCy(['search/input', 'search/button']).should('have.length', 2);
});

Using the cypressTag helper

import { cypressTag } from 'cypress-helper-getcy';

const tag = cypressTag('search');

it('finds my tagged subjects', () => {
  cy.getCy(tag()).should('be.visible');
  cy.getCy(tag('input')).type('term');
  cy.getCy(tag('button')).click();
  cy.getCy(tag(['input', 'button'])).should('have.length', 2);
});

Using the getCypressTag helper

import { getCypressTag } from 'cypress-helper-getcy';

const get = getCypressTag('search');

it('finds my tagged subjects', () => {
  get().should('be.visible');
  get('input').type('term');
  get('button').click();
  get(['input', 'button']).should('have.length', 2);
});

Note: See tests for more examples.