I am trying to write an assertion in my Cypress test that checks that the date format is mm/dd/yyyy.
Right now, the assertion is failing and I think it's because there is white space at the start and end of the date, as you can see below. To extract the value from the html, I used an alias. When I hard code the date and use contain instead of match, it passes, but when I use Regex instead and use match, it fails. Can somebody tell me what can be wrong? How can I deal with white space when writing an assertion?
I am testing this using Cypress on a web app built in Angular.
HTML
<mat-cell class="mat-mdc-cell mdc-data-table__cell cdk-cell cdk-column-Test-Date mat-column-Test-Date ng-star-inserted" role="cell"> 10/10/2024 </mat-cell>
Cypress Test
cy.get("cdk-column-Test-Date").as("testDate");
cy.get("@testDate").should("match", /^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d$/);
The first obvious mistake is you are testing the whole element, not it's text.
Use invoke('text')
to test the text of the element.
const date_regex = '/(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/';
cy.get("cdk-column-Test-Date")
.invoke('text')
.should('match,' date-regex)
2nd thing - why do you think the alias strips spaces? It does not, you should add trim()
method. Forget about aliasing.
cy.get("cdk-column-Test-Date")
.invoke('text')
.then(text => text.trim())
.should('match', date-regex)