javascriptpostmanweb-api-testing

Postman test script for matching 2 key values inside of each item


Here is how the response tested looks like:

[
    {
        "label": "Summer '14",
        "url": "/services/data/v31.0",
        "version": "31.0"
    },
    {
        "label": "Winter '15",
        "url": "/services/data/v32.0",
        "version": "32.0"
    },
    {
        "label": "Spring '15",
        "url": "/services/data/v33.0",
        "version": "33.0"
    }
]

Now, I want to test to make sure that each URL key for each item contains a value matching the following value: "/services/data/v" + the version number that comes after it must be exactly the same as the version number given for the same items as the value for the version key.

I've actually created a piece of script that is receiving a passed result:

pm.test("URL matches the format and version matches the version key", function () {
    const response = pm.response.json();
    
    response.forEach(item => {
        // Extract version from the URL
        const urlPattern = /^\/services\/data\/v(\d{2}\.\d)$/;
        const match = item.url.match(urlPattern);

        // Verify the URL follows the expected format
        pm.expect(match).to.not.be.null; // Ensure the URL matches the pattern

        // Extract the version from the URL if the pattern matched
        const urlVersion = match ? match[1] : null;

        // Verify the extracted version matches the version key
        pm.expect(urlVersion).to.eql(item.version); 
    });
});

Now, what I would need is actually a confirmation from someone who is experienced in Postman testing, or generally in JavaScript. Is this script is actually doing what I am expecting it to do as described above?


Solution

  • Yes the regex that you have created matches with /services/data/v and you are correctly checking the version.