Cypress: child command subject seems not to be an element

Viewed 2320

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?

2 Answers

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.

Try to use

cy.wrap(subject)

For me that was the trick.

Related