2
votes

I am trying to check mat-checkbox element with the cypress check() method and even if add force parameter. Example:

Cypress.Commands.add('changeEmailLayoutCheckbox', () =>
  cy
    .get(EMAIL_LAYOUT_CHECKBOX)
    .check({ force: true })
);

I am getting the following error

cy.check() can only be called on :checkbox and :radio. Your subject is a: <mat-checkbox

The message is quite clear but the problem is that I emit some event on mat-checkbox change, which set parameters to my request. I also have tried with click() but those not trigger mentioned event.

3
Off the top of my head, I think there is a check box that is a child of the mat-checkbox, inspect your html and you will see it I think, you need to select the check box within it. I did not put this as an answer, but I think I have ran into this before with Angular Material.Maccurt
You are right I have to go deeper to find that input within mat-checkbox. You can put it as the answer I will mark it as good one ;)Stefan
will do. I appreciate the pointsMaccurt
did it work out for you?Maccurt

3 Answers

5
votes

The check box is a child element of the mat-checkbox. You will need to select the inner child and click on that. I had to force it true to work. I will see if there is a better way to do that.

describe('how to check mat-checkbox', () => {
  it('check the input', () => {       
    cy.visit('https://material.angular.io/components/checkbox/overview');
      cy.get('#mat-checkbox-1-input').click({force:true});
      //**** OR ***********   
      cy.get('#mat-checkbox-1').find('input').click({force:true});    
  });
});
0
votes

According to my experiments, the syntax can remain quite simple, without forcing, as long as the right element is chosen.

Sum up example:

<div id="parent">
  <mat-checkbox ...></mat-checkbox>
  <!-- assuming there is no other input or mat-checkbox here -->
</div>
cy.get('#parent mat-checkbox').click()       # interact
cy.get('#parent input').should('be.checked') # check state

DOM Example

Here is how it looks like in the DOM, for an app:

enter image description here

0
votes

A simple solution following cypress's best practices

Add a data-cy (best practices: https://docs.cypress.io/guides/references/best-practices#Selecting-Elements) or some other unique selector to the mat-checkbox element like so:

<mat-checkbox data-cy="some-unique-reference">...</mat-checkbox>

Since the actual input element (the checkbox itself) is a child of the mat-checkbox - in your spec file do:

cy.get('[data-cy="some-unique-reference"] input').should('be.checked');
cy.get('[data-cy="some-unique-reference"] input').click();