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

Ensuring that the height of this specific div is set to 100% using

Is there a way to utilize the .height() method to fetch the height of each individual .post element and then assign it to the corresponding .left element? I have tried using this() but haven't been able to find a solution... Currently, my jQuery code ...

React using Firebase: Receiving error "Cannot use import statement outside a module"

I've been following a helpful tutorial on setting up firebase authentication with React. However, I encountered some issues while trying to configure Firebase. I have created a firebase.js file as per the tutorial instructions: import firebase from &q ...

Retrieve the string data from a .txt document

I am facing an issue with my script that retrieves a value from a .txt file. It works perfectly fine when the value is a number, but when trying to fetch text from another .txt file, I encounter the "NaN" error indicating it's not a number. How can I ...

Breaking down an array into function arguments in TypeScript/JavaScript

I am working with an array of object instances that have different types. var instances: any = []; instances["Object1"] = new TypeA(); instances["ObjectB"] = new TypeB(); Each type has its own methods with unique names and varying numbers of arguments. I ...

What is the best way to finish up the JavaScript code below?

Having just started learning JavaScript, I am struggling to figure out how to use JavaScript to clear the text in a text box and move it below the box when a user starts typing. I've been watching this tutorial http://codepen.io/ehermanson/pen/KwKWEv ...

Error in Postman: Express and Mongoose throwing 'name' property as undefined

While trying to create and insert 'user' JSON documents according to the model below, upon sending a POST request to localhost:3000/api/student, I encountered an error using Postman: TypeError: Cannot read property 'name' of undefined ...

arranging data in html table columns using angular 2

I am facing a challenge where I require each column of a table to be sorted in ascending order every time it is clicked. The sorting logic implemented is a standard JavaScript method. While this method works well in most scenarios, it encounters issues whe ...

Issue with Material-ui autocomplete not updating its displayed value according to the value prop

My task involved creating multiple rows, each containing a searchable Autocomplete dropdown populated through an API, along with other fields. Everything was functioning perfectly until I encountered an issue when deleting a row from the middle. After dele ...

Having trouble locating the search bar element on Walmart's website?

I'm currently working on a bot that needs Selenium to interact with the search bar on Walmart's website, where it will input the name of a specific product and perform a search. However, I've encountered an issue where no matter what method ...

Create a React component using the value stored within an object

I am interested in creating an object: import React from "react"; import { Registration } from "../../"; const RouteObj = { Registration: { route: "/registration", comp: <Registration /> } }; export default RouteObj; Next, in a separat ...

The act of sending back Null from the Array.map() function

I've been attempting to retrieve data from a JavaScript object using the array.map() function. However, the result I'm receiving is null. I'm confused as to what the issue might be. Here's the object: export const Course = [ { co ...

D3.js Issue: The <g> element's transform attribute is expecting a number, but instead received "translate(NaN,NaN)"

I encountered an error message in my console while attempting to create a data visualization using d3. The specific error is as follows: Error: <g> attribute transform: Expected number, "translate(NaN,NaN)". To build this visualization, I ...

Use the sed utility to modify a specific value within a .spec file

Is there a way to modify the value in the .spec file using sed? I need to change the $nmatch value of build to something different, like "build1.1". { "files": [ { "aql": { "items.find": { "repo&qu ...

Converting JavaScript code into PHP syntax

I'm curious about code organization. The original code in this snippet is functioning properly: <?php if (isset($_POST['submit'])){ ... ... $invalidField = 2; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD ...

Ways to verify if the CSS background-color is set to white?

I am looking for a solution: $('*').click(function() { if($(this).css("background-color") == "#ffffff") { $(this).css("background-color") == "#000000" } });​​​​ that will execute on click of a specific cla ...

Numeric keypad causing issues with setting minimum and maximum lengths and displaying submit button

I designed a password pin page that resembles a POS NUMPAD for users to enter their password. I am struggling to make the condition specified in the JavaScript function properly. Rule: Hide the submit button if the minimum input is less than 4 characters ...

Having trouble retrieving data from a JSON object in React/Redux?

It seems like there might be something obvious that I'm missing here - but I can't seem to figure out how to access the JSON data. I have a Container component: class About extends Component { componentDidMount(){ const APP_URL = 'htt ...

Dynamic Content Sorting with JavaScript and jQuery

I am presenting various courses that are available, and I am utilizing JavaScript/jQuery to display or hide them based on element classes. You can view the page here. Currently, the script conceals all content on the page and then reveals items that matc ...

Is it possible to transmit a WebRTC frame to a Python script?

I recently built my first web app using Python and Django, which displays webcam frames of clients. 'use strict'; // For this project, I am only streaming video (video: true). const mediaStreamConstraints = { video: true, }; // Video element ...

Formatting dates in JavaScript

When using the jQuery datepicker, my goal is to set a minimum and maximum date range for users to select from. I also need to ensure that the date format is based on the user's locale. In this case, there are two date fields: Start date and End date. ...