skip to Main Content

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


  1. Using (w|0-9)* seems like an unintended repetition as 0-9 matches that literally. If you want to match a digit the notation could be [0-9] but that is also matched by w

    Using a case insensitive pattern with /i where the part of the pattern matches at least 3 characters, and using w+ to match 1 or more word characters (at the id seems to be always present)

    //[a-z0-9][a-z0-9-]+[a-zA-Z0-9]/w+/i
    

    Regex demo

    If you also want to match a single character, and no consecutive hyphens --

    //[a-z0-9]+(?:-[a-z0-9]+)*/w+
    

    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 chars

    Regex demo

    Login or Signup to reply.
  2. 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 variables

    Naming variables in JavaScript

    • Variable names must start with a letter, an underscore ( _ ) or a dollar sign ( $ ).
    • Variable names cannot contain spaces.

    which gives regex of

    //([a-z|$|_][a-z|-|d]*)/(d+)/i
    

    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 the id

    /<the-regex>/i

    • ignore-case modifier removes the need for [A-Z] in the regex

    Test

    This is the test in regex101

    // these should pass
    /customerdetails/1
    /customer/2
    /customer/321
    /order/555
    /_product/234
    /$orderitem/345
    /$order-item/345
    /$order1-item/345
    /$/1
    
    // these should fail
    /order/a12
    /5product/123
    /$order item/432
    /-order/123
    

    If you want a more relaxed approach, this could be the simplest regex:

    /w+/d+
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search