`Cypress.Commands.add` type doesn't take into account `prevSubject` to define the type of the custom command
See original GitHub issueCurrent behavior
declare global {
namespace Cypress {
interface Chainable {
/**
* Custom command to select DOM element by data-cy attribute.
* @example cy.dataCy('greeting')
*/
dataCy<E extends Node = HTMLElement>(value: string): Chainable<JQuery<E>>;
}
}
}
Cypress.Commands.add(
'dataCy',
{ prevSubject: 'optional' },
(subject, value) => {
return cy.get(`[data-cy=${value}]`, {
withinSubject: subject,
});
},
);
subject
and value
are inferred as any
as prevSubject
isn’t taken into account and TS expect a single param
If value
is removed, the first param becomes string
which is wrong
The same problem applies to child commands
Desired behavior
Types should take into consideration prevSubject
and use it into a conditional to provide correct typings
There may be other edge cases with element
| document
| window
Test code to reproduce
This test is wrong, it should be
Cypress.Commands.add('newCommand', { prevSubject: true }, (subject, arg) => {
// $ExpectType string
arg
return
})
Cypress Version
9.0.0
Other
No response
Issue Analytics
- State:
- Created 2 years ago
- Reactions:14
- Comments:7
Top Results From Across the Web
Custom Commands - Cypress Documentation
Cypress comes with its own API for creating custom commands and overwriting existing commands. The built in Cypress commands use the very same...
Read more >Custom Commands in Cypress - Tools QA
What are custom commands in Cypress and the recommended best practices? How to add Custom commands documentation in Cypress Intellisense?
Read more >Navigating Cypress Custom Commands | by Tod Gentille
First create a type that describes the new command. The type StringNumberFn specifies a function that takes a string and a number, and...
Read more >Useful custom Cypress commands - Ron Valstar
Some useful Cypress custom commands to make your tests cleaner.
Read more >Cypress custom command is not recognized when invoked
For me it worked when I added the type signature of the custom command in the file cypress/support/index.d.ts. For more information visit: ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
We have the same issue 😢
Also this test for optional subject should be added: