1

In my Cypress tests, I need to verify that a value is in a GUID format.

Here's an example of the value returned: fbb4f73c-0e3b-4fda-ad0a-81a1b8a8c72f

I've tried asserting using a RegEx below:

resultString = Regex.Replace(subjectString,
            "(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$",
            "'$0'");

        expect(myXhr.response.body.Id).should('contain', /resultString/)

But I get the following error message:

Invalid Chai property: should

user9847788
  • 2,135
  • 5
  • 31
  • 79
  • 1
    See [this post](https://stackoverflow.com/a/49140751/3832970). Guid validation regex is [here](https://stackoverflow.com/questions/11040707/c-sharp-regex-for-guid). – Wiktor Stribiżew Apr 14 '21 at 16:43
  • Thanks @WiktorStribiżew for the above links. I've tried to add this to my test, but I'm getting an error now. I've updated my question with this code & error message. – user9847788 Apr 14 '21 at 17:01

2 Answers2

1

You have to use .match to compare your value against a RegEx. You can check the Cypress Assertions Page for all the assertions that cypress supports.

expect(myXhr.response.body.Id).to.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
  • Does this work in JavaScript? I'm getting `Regex is not defined` error message – user9847788 Apr 14 '21 at 17:22
  • Yes, it works in JS. Try by directly using the Regex value inside Match. – Alapan Das Apr 14 '21 at 17:24
  • Getting this error now `Invalid regular expression: /(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$/: Invalid group (45:45)`. I'll check if the regex is incorrect – user9847788 Apr 14 '21 at 17:25
  • Yes I think there is some issue with the regex. I have used this in my tests against a regex and it works. – Alapan Das Apr 14 '21 at 17:26
  • 1
    So your assertion works as expected with this new regex pattern: `/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i`. – user9847788 Apr 14 '21 at 17:31
1

You might find it easier to use the chai-uuid library.

Cypress adds it to the build, but I think there's a bug that prevents it being used out of the box. You can however extend chai - see the example recipe extending-cypress__chai-assertions for full info.

Simplest approach is

npm install -D chai-uuid

or

yarn add -D chai-uuid

then the test

chai.use(require('chai-uuid'));

it('validates my uuid', () => {

  expect('fbb4f73c-0e3b-4fda-ad0a-81a1b8a8c72f').to.be.a.guid()
  expect('fbb4f73c-0e3b-4fda-ad0a-81a1b8a8c72f').to.be.a.uuid()
  expect('fbb4f73c-0e3b-4fda-ad0a-81a1b8a8c72f').to.be.a.uuid('v4')

  cy.wrap('fbb4f73c-0e3b-4fda-ad0a-81a1b8a8c72f')
    .should('be.a.guid')                          

  cy.wrap('fbb4f73c-0e3b-4fda-ad0a-81a1b8a8c72f')
    .should('be.a.uuid', 'v4')                       // same as 'be.a.guid'

})
Richard Matsen
  • 20,671
  • 3
  • 43
  • 77