1

The client app under testing generates UUIDs for certain ID fields, hence the POST requests to the API are not predictable.

I could compare property by property and just skip those ID fields, but this is quite cumbersome as the request bodies will become quite complex. So my idea was to place the IDs from the request body into the expected value, but I couldn't find a way. So I need to refer to the request body in the "should" function below to have something like 'id: requestBody.id' where the placeholder << UUID >> is.

cy.route('POST', '/property').as('post-property');
cy.wait('@post-property')
  .its('requestBody')
  .should('deep.equal', {
    id: << UUID >>,
    name: 'Test Property',
    nr: 'P01',
    property_type_id: 1001,
    address: {
      id: << UUID >>,
      address_type_id: 1000,
      street: 'Musterstrasse',
      street_nr: '27',
      zip: '8000'
    },
  });
G. Marc
  • 4,987
  • 4
  • 32
  • 49

2 Answers2

0

Cypress bundles the popular Chai assertion library so you can achieve pattern matching by additionally installing chai-match-pattern.

Step 1: npm i chai-match-pattern --save-dev

Step 2: In support/index.js, dependency injection:

const chaiMatchPattern = require('chai-match-pattern');
chai.use(chaiMatchPattern);

Step 3: Use matchpatten as:

cy.route('POST', '/property').as('post-property');
cy.wait('@post-property')
.its('requestBody')
.should('matchPattern', {
  id: /appropriate_regex/,
  name: 'Test Property',
  nr: 'P01',
  property_type_id: 1001,
  address: {
    id: /appropriate_regex/,
    address_type_id: 1000,
    street: 'Musterstrasse',
    street_nr: '27',
    zip: '8000'
  },
});

Example from my test:

cy.wrap({
    id: '98517765-7b53-4737-b8a3-e256858848a4',
}).should('matchPattern', {
    id: /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i,
});

Pattern taken from Ivan Gabriele's answer

Test Screenshot:

enter image description here

Sree.Bh
  • 1,751
  • 2
  • 19
  • 25
0

Perhaps remove the id from the object before testing, something like

  .its('requestBody')
  .then(requestBody => { 
    const { id, ...rest } = requestBody; 
    return {...rest}; 
  })
  .should('deep.equal', {
    name: 'Test Property',
    nr: 'P01',
    property_type_id: 1001,
    address: {
      id: << UUID >>,
      address_type_id: 1000,
      street: 'Musterstrasse',
      street_nr: '27',
      zip: '8000'
    },
  });

You may need to wrap the truncated object, e.g return cy.wrap({...rest});, I'm not sure if Cypress wraps it for you or not.