Validating date parameter in Wiremock request - How to ensure dynamic date matching during testing?

Looking for some assistance in verifying that the date in a request is exactly Today. I've tried various methods from the documentation, but haven't achieved the desired outcome yet. Calling out to any helpful souls who can guide a junior QA through this challenge :)

One approach I attempted (suggested by a colleague and seems promising based on the documentation)

{
    "request": {
        "urlPath": "/test/calc",
        "method": "POST",
        "headers": {
            "Accept": {
                "equalTo": "application/json"
            },
            "Content-Type": {
                "equalTo": "application/json"
            }
        },
        "bodyPatterns": [
            {
                "matchesJsonPath": {
                    "expression": "$.addDate",
                    "and": [
                        {
                            "before": "now + 1 days"
                        },
                        {
                            "after": "now - 1 days"
                        }
                    ]
                },
                "equalToJson": {
                    "RequestBody": {
                        "order": {
                            "positionList": [
                                {
                                    "id": 1,
                                    "addDate": "${json-unit.any-string}",
                                    "qty": 1
                                }
                            ]
                        }
                    }
                },
                "ignoreArrayOrder": false
            }
        ]
    },
    "response": {
        "transformers": [
            "response-template"
        ],
        "status": 200,
        "bodyFileName": "v1/test-service-mock-response.json",
        "headers": {
            "Content-Type": "application/json"
        }
    }
}

Hoping to validate the parameter "addDate" in the request. The date format should be like "addDate": "2022-03-31".

*Also experimented with this variation "addDate": "{{now format='yyyy-MM-dd'}}" without success. Wiremock didn't seem to match requests with this setup.

Answer №1

When I was looking to accomplish the same task, I stumbled upon this question about matching a request based on a dynamic date value in the request body.

Following your guidance led me in the right direction, and I successfully implemented it by combining multiple bodyPatterns. For your scenario, the solution should be as follows:

    "bodyPatterns": [ {
      "matchesJsonPath": {
        "expression": "$.RequestBody.order.positionList[0].addDate",
        "and": [
          {
            "matches": "\\d{4}-\\d{2}-\\d{2}"
          },
          {
            "equalToDateTime": "now",
            "truncateExpected": "first hour of day"
          }
        ]
      }
    }, {
      "equalToJson": {
        "RequestBody": {
          "order": {
            "positionList": [
              {
                "id": 1,
                "addDate": "${json-unit.any-string}",
                "qty": 1
              }
            ]
          }
        }
      },
      "ignoreArrayOrder": false
    } ],

The first bodyPattern utilizes the expression within matchesJsonPath to locate the addDate field (checking only the first element of the array for simplicity because that's sufficient for your use case) and validates if it is in the correct format and matches the current date.

The second bodyPattern essentially mirrors what you already had and employs equalToJson to match the remaining portions of the request body, while ensuring that addDate is a string.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for me to hand over control to a child process and retrieve the result in Node.js?

Recently, I encountered an issue where multiple simultaneous GET requests to my Node.js server caused it to become overwhelmed and unresponsive, leading to timeouts for clients (503, service unavailable). Upon thorough performance analysis, I discovered t ...

The server is unable to receive lists that are included within the JSON object being passed in

Below are the data contracts utilized in the function. public class ResumeSkillsListDataContract : IResumeSkillsListDataContract { public IList<ISkillDataContract> KnownSkillsList { get; set; } public IList<ISkillDataContract> BadSkill ...

Struggling to retrieve data from AJAX call

I'm having trouble accessing the data returned from a GET AJAX call. The call is successfully retrieving the data, but I am unable to store it in a variable and use it. Although I understand that AJAX calls are asynchronous, I have experimented with ...

Export web application content to PDF through rendering on the server side

Our interactive web application, which includes multiple d3 charts, is built with vue. Currently, I am able to export our webpage to a PDF file by utilizing canvg and html2canvas to convert the content into PNG format. The PNG file is then transmitted to t ...

What are some React component libraries compatible with Next.js 13.1?

I'm exploring Next.js and experimenting with version 13.1 and the new app directory. Is it feasible to accomplish this without sacrificing the advantages of server controls? An error message I encountered states: You're attempting to import a c ...

Should I fork and customize npm package: Source or Distribution? How to handle the distribution files?

Currently, I am in the process of developing a VueJS web application. Within this project, there is a module that utilizes a wrapper for a JavaScript library obtained through npm and designed to seamlessly integrate with VueJS. However, it doesn't com ...

Dismiss MUI Snackbar notification and execute action upon pressing a key

A custom notification system has been developed, utilizing the material ui Snackbar with both an action button and a close button. The objective is to implement a listener event for the "enter" key in order to trigger the specific notification's actio ...

What is the best way to transfer data from a parent component to a child component in ReactJs?

When dealing with nested react elements, how can you pass values from the parent element to a child element that is not directly inside the parent element? React.render( <MainLayout> <IndexDashboard /> </MainLayout>, document.b ...

Is it possible to trigger this Angular function upon page load?

I have an async function called getDataStandard() that I want to execute without the need for a click event. Can someone please guide me on how to achieve this as I am new to Ionic? async getDataStandard() { let loading = await this.loadingCtrl.create ...

What are the best practices for effectively utilizing the nodejs Stream API?

I am currently working on an application that reads input from various sources, including files, sockets, and other parts of the same program that produce buffers or strings. While I have successfully handled sockets and files using node's Stream API ...

Finding the index and value of a specific HTML element with jQuery click event

I'm currently working on creating an Ajax function to delete items from a list using Jquery ajax. Here is the HTML structure: <ul> <li><a class="del"><span style="display:none;">1</span></a></li> <li& ...

Harness the power of electrons with the simple push of a button - initiating program execution

Recently, I delved into Electron with the desire to create a small application for myself. This app would allow me to run different programs or games by simply clicking on a link. My goal is to have the program/game start automatically when I open the Ele ...

Encountered an issue during the installation of react router - in need of assistance to resolve the error

Encountering an Error Error Message when Installing React Router DOM: npm WARN: The use of global `--global` and `--local` is deprecated. Use `--location=global` instead. npm ERR! code EPERM npm ERR! syscall mkdir npm ERR! path D:\ npm ERR! errno -404 ...

Challenges with 'this' reference in a requireif causing Vuelidate complications

     Need help with vuejs component using vuelidate and validations:     validations: {      invoice: {          dueDate: {              required,          },          tax: {              require ...

Developing a digital sound system using JavaScript

I am currently in the process of developing a music player. Below is my HTML code: <div id="main"> <div id="list" draggable="true"> </div> <div id="player"> <div id="buttons"> < ...

a guide to presenting information in a horizontal layout within a single table using the Laravel framework and Vue.js

I have 2 tables: table 1 ________________ | name_id name | | 1 john | | 2 heaven | |_______________| table 2 _______________________ | id name_id product | | 1 1 bag | | 2 1 shoes | |______ ...

React - dynamically injecting external logic during execution

My goal is to modularize my React application by loading additional logic (such as containers/components) dynamically from an external .js file during runtime. For instance, I want to be able to introduce a new tab with completely different functionality o ...

A guide to accessing REST services in AngularJS using basic authentication

I currently have a REST service up and running on my server. Using Chrome Postman, I am able to access this service with Basic Authentication. However, I now want to build a user interface in AngularJS to display the data received from the REST service. T ...

Getting the ajax response by utilizing a custom attribute within a php loop is definitely a handy trick

Currently working on integrating ajax with php. I have a set of buttons within a loop, and I am trying to display or fetch data (number) in the correct place/div using the "attr" method in jQuery. However, it seems that it is not functioning as expected on ...

The AJAX function failed to trigger another JavaScript function after successfully completing its task

Trying to figure out how to execute a function after successful AJAX post request. The function I want to call is: function col() { var $container = $(".post-users-body"); $container.imagesLoaded(function() { $container.masonr ...