Home > database >  Tests in Postman for requests that return random values
Tests in Postman for requests that return random values

Time:08-25

I'm learning Postman. I have a query that returns random values from a key:

   GET https://apitest.backendless.com/A1DA5DF0-8D22-BAC4-FF56-9A0074DC9B00/8834B7F8-88BD-4472-9051-71BE31A3EE5B/hive/rootKeys/set/root1/random?count=2

You can use a working request. The key contains the values ["1", "2", "3", "4", "5"]

The question is: how do I write tests for a query that returns random values? Here is a test

let jsonData = JSON.parse(responseBody);
    pm.test("Random values", function(){
        pm.expect(jsonData).to.eql(["1", "2"])
})

won't do because it might return ["3", "5"]. How then to check the validity of the request?

CodePudding user response:

A very basic check could be something like this:

let response = pm.response.json();

pm.test("Random Number Check", () => {
    pm.expect(response, "Response contains a number not in the array").to.contain.oneOf(["1", "2", "3", "4", "5"]);
});

CodePudding user response:

I've created a postman request for you to test directly (https://www.postman.com/southlondon/workspace/playground/request/19391207-0bbb11cb-249c-4fe2-963e-5b73b8cabc9b). It sends a payload with a random array with values from 1 to 5. You can click send several times and see the differences. You can open that link and test it. The test itself tries to validate that only values from 1 to 5 exist in the array:


pm.test("Check that array only contains numbers from 1 to 5 ", function () {
    let jsonData = pm.response.json();
    let array = jsonData.data
    array.every( x => x >= 1 && x <=5 )
});

This covers scenarios where the data would send a value outside the range you described.

  • Related