Arnon Axelrod
Arnon Axelrod

Reputation: 1672

Cypress custom command for an array-like prevSubject

I'm writing a custom command getFirst, which returns the first element according to a given predicate. Everything works fine, but I wanted to specify a specific prevSubject parameter instead of true, in order to prevent improper usage.

In the documentation, the only mentioned options are false, true, optional, element, document or window, but it doesn't say how to specify an array-like structure, like the cy.each does.

Any idea how that could be done?

Here's my code:

Cypress.Commands.add('getFirst', {prevSubject: true},
<TSourceSubject, TPredicateSubject, TResult>(
    subject: TSourceSubject,
    getPredicateSubject : (sourceSubject : TSourceSubject) => Chainable<TPredicateSubject>,
    predicate: (predicateSubject: TPredicateSubject) => boolean) => {
cy.wrap(subject).each((item : TSourceSubject) => {
    getPredicateSubject(item).then<TPredicateSubject>((predicateSubject : any) => {
        if (predicate(predicateSubject)) {
            cy.wrap(item).as('getFirstItemAlias');
        }
    });
});

return cy.get('@getFirstItemAlias');

});

PS: If someone has an idea how to get rid of the getFirstItemAlias alias, or if there's some way to make its scope local, it would be very helpful too.

Thanks!

Upvotes: 0

Views: 1363

Answers (1)

Brendan
Brendan

Reputation: 4659

I was curious so I looked at Cypress' source code to see how this was done.

There aren't any additional undocumented options for prevSubject: https://github.com/cypress-io/cypress/blob/develop/packages/driver/src/cy/ensures.coffee#L21-L39

cy.each() is using { prevSubject: true } and explicitly checking that the subject is an array: https://github.com/cypress-io/cypress/blob/0f73bb7e1910296469f3f631a7f2303f4ecd035e/packages/driver/src/cy/commands/connectors.coffee#L374-L383

Upvotes: 1

Related Questions