A simple Cypress command for getting elements via data-cy
attributes.
DEPRECATED: Using test id's to get elements has more or less been replaced by the much better practice of using queries based on accessibility. I recommend using something like Cypress Testing Library instead.
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. 👍
npm install --save-dev cypress-helper-getcy
// E.g. in cypress/support/index.js
import 'cypress-helper-getcy';
<form data-cy="search">
<input data-cy="search/input" />
<button data-cy="search/button">Search</button>
</form>
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.
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);
});
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);
});
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.