I am interested in developing a customized Cypress find
command that can make use of a data-test
attribute.
cypress/support/index.ts
declare global {
namespace Cypress {
interface Chainable {
/**
* Creating a custom command to locate a DOM element by its data-test attribute.
* @example cy.getByTestId('element')
*/
getByTestId(selector: string): Chainable<JQuery<HTMLElement>>;
/**
* Creating a custom command to find a DOM element using its data-test attribute.
* @example cy.findByTestId('element')
*/
findByTestId(selector: string): Chainable<JQuery<HTMLElement>>;
}
}
}
cypress/support/commands.ts
Cypress.Commands.add('getByTestId', (selector, ...args) => {
return cy.get(`[data-test=${selector}]`, ...args);
});
Cypress.Commands.add(
'findByTestId',
{ prevSubject: 'element' },
(subject, selector) => {
return subject.find(`[data-test=${selector}]`);
}
);
It is important to note that subject
is of type JQuery<HTMLElement>
and not
Cypress.Chainable<JQuery<HTMLElement>>
, causing subject.find
to not be chainable with other methods.
I am encountering the following errors from TypeScript.
No overload matches this call.
Overload 1 of 4, '(name: "findByTestId", options: CommandOptions & { prevSubject: false; }, fn: CommandFn<"findByTestId">): void', gave the following error.
Overload 2 of 4, '(name: "findByTestId", options: CommandOptions & { prevSubject: true | keyof PrevSubjectMap<unknown> | ["optional"]; }, fn: CommandFnWithSubject<"findByTestId", unknown>): void', gave the following error.
Overload 3 of 4, '(name: "findByTestId", options: CommandOptions & { prevSubject: "element"[]; }, fn: CommandFnWithSubject<"findByTestId", JQuery<HTMLElement>>): void', gave the following error.ts(2769)
cypress.d.ts(22, 5): The expected type comes from property 'prevSubject' which is declared here on type 'CommandOptions & { prevSubject: false; }'
Intended usage
cy.getByTestId('some-element')
.findByTestId('some-test-id')
.should('have.text', 'Text');
How can I resolve this issue?