Search code examples
javascriptpostmanpostman-collection-runner

How to compare two URLs in JavaScript Postman Runner


I want to compare two URLs: the first from the response and the second from the uploaded CSV file.

I want to check that the URL in the response is the same URL linked to the requested row in the CSV file.

The request body

{
"brandTrigram": "{{brandTrigram}}",
"countryId": "{{countryId}}",
"languageId": "{{languageId}}"
}

Tests

pm.test("Check returned data", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.URL).to.eql(pm.variables.get("URL"));
});

The CSV file

brandTrigram,countryId,languageId,URL
car,ca,eng,https://ca.cartier.com/en-ca/others/privacy-policy.html
car,ae,ara,https://www.cartier.ae/ar-ae/%D8%BA%D9%8A%D8%B1-%D8%B0%D9%84%D9%83/%D8%B3%D9%8A%D8%A7%D8%B3%D8%A9-%D8%A7%D9%84%D8%AE%D8%B5%D9%88%D8%B5%D9%8A%D8%A9.html

I get the following error for the first iteration in the CSV file:

Check returned data | JSONError: Unexpected token 'h' at 1:1 https://ca.cartier.com/en-ca/others/privacy-policy.html ^

So the javascript test is not doing the job of comparison we want :/ , how can i solve that ?

DATA PREVIEW


Solution

  • If your response body is:

    {
        "URL": "some URL"
    }
    

    The test could be:

    pm.test("Check returned data", function () {
        var jsonData = pm.response.json();
        pm.expect(jsonData.URL).to.eql(pm.iterationData.get("URL"));
    });
    

    Using pm.iterationData.get() ensures you're getting the value from that scope and avoids issues if you have that variable name in a different scope.

    I don't know what the response body structure is so this is a guess based on seeing jsonData.URL in the question.

    EDIT

    It looks like the response is plain text and not a JSON object so using either pm.response.json() or jsonData.URL is incorrect.

    pm.test("Check returned data", function () {
        var response = pm.response.text();
        pm.expect(response).to.include(pm.iterationData.get("URL"));
    });