I have a fillInput() function that takes a selector and a value as parameters, then:
clear the the input via cy.get(selector).clear()
then fills the input value via cy.get(selector).type(value)
As far as I know, this is really some sort of anti-pattern and a cypress command should be the way to go.
So, reading about child commands, I came out with this command that should do the same as my fillInput() utility function:
Cypress.Commands.add('fillInput', {prevSubject: 'element'}, (subject, value) => {
subject.clear();
subject.type(value);
});
However, when I try this in a spec via:
cy.get('#my-selector').fillInput('my-value');
I get this error in the cypress browser console:
TypeError: subject.clear is not a function
In the docs, cy.get() is said to yield a DOM Element, and the {prevSubject: 'element'} should make subject to be the same type (as far as I understand this).
However, subject seems to be a different type and methods that work on elements like type() or ' clear()or ' should() does not work on child command subjects.
How can I get the subject of my child command to act as a Dom Element?
While investigating to post the question, I came up with a simple solution to this problem. The subject is an object which has a selector, so you can use that selector with cy.get(subject.selector) to get the Dom Element:
Cypress.Commands.add('fillInput', {prevSubject: 'element'}, (subject, value) => {
cy.get(subject.selector).clear().type(value);
});
I think this is not a lot of clear and more people may have this issue, so I leave my solution here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With