user9847788
user9847788

Reputation: 2433

How to check mat-checkbox based on label during Cypress test?

Is it possible to check a mat-checkbox in a Cypress test based on it's label text?

Below is the HTML for the checkbox:

enter image description here

I have several checkboxes to test, so I want to re-use code to do something like - When I check the 'Advanced search' checkbox, When I check the 'Basic search' checkbox, etc.

Upvotes: 0

Views: 1674

Answers (2)

Fody
Fody

Reputation: 32052

The <mat-checkbox> can be accessed by label text with a simple .contains(), but you must use .click() instead of .check().

cy.contains('mat-checkbox', 'Advanced search')
  .click()

Using .check() gives you the error

<input> is being covered by another element <label>

Upvotes: 1

jjhelguero
jjhelguero

Reputation: 2555

If the label only holds one check box for Advanced search, then you can use .contains() with label as the selector along with text of the checkbox, then .find() the checkbox to check.

// this will get label element
cy.contains('label', /advanced search/i)
  // this will get checkbox input
  .find('input[type=checkbox]')
  .check()

Here is a working example.

Upvotes: 1

Related Questions