So I wrote a method in Cypress using Regular Expressions that will dynamically assert any pathname and its ID I pass the following way:
public assertUrlPathWithID(path:string) {
cy.url().should("match", //[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]/(w|0-9)*/);
};
assertUrlPathWithID("customerdetails")
The test is passing, but I was was wondering if there was a cleaner way of doing it or a different approach that is more effective. Essentially, I want to assert that the url path using regex for the routes on my application
/customerdetails/id
/customer/id
/order/id
2
Answers
Using
(w|0-9)*
seems like an unintended repetition as0-9
matches that literally. If you want to match a digit the notation could be[0-9]
but that is also matched byw
Using a case insensitive pattern with
/i
where the part of the pattern matches at least 3 characters, and usingw+
to match 1 or more word characters (at the id seems to be always present)Regex demo
If you also want to match a single character, and no consecutive hyphens
--
The pattern matches:
/[a-z0-9]+
Match/
and 1+ chars a-z0-9(?:-[a-z0-9]+)*
Optionally repeat-
and 1+ chars a-z0-9/w+
Match/
and 1+ word charsRegex demo
Typically URL routes will be of format
/<resource>/<numeric-id>
A
<resource>
would originate in javascript, and probably needs to follow the rules for javascript variableswhich gives regex of
Breaking it down,
<resource>
[a-z|$|_]
handles first char requirement[a-z|-|d]*
handles subsequent chars. Conventionally-
is allowed in a variable name<numeric-id>
(d+)
because only digits should be in theid
/<the-regex>/i
[A-Z]
in the regexTest
This is the test in regex101
If you want a more relaxed approach, this could be the simplest regex: