Hello. I have a task in Postman. When I send Get request I also have to right test for “Check that the number of characters “” in the body of the response does not exceed (less than or equal to) 700.”
You could try something like this in the ‘Test’ tab.
//parse json
const x = pm.response.json();
//stringify the response and count the length
let y = JSON.stringify(x).length;
//output to console
console.log(y);
//test the length
pm.test("Response is less than 700 characters", function () {
pm.expect(y).to.be.below(700);
});
Hello. Seems it worked). But interesting how to make it with if … .else (in else case it writes some other text)
It depends on what you are trying to achieve… but as an example of an if/else you could do something like this;
//parse json
const x = pm.response.json();
//stringify the response and count the length
let y = JSON.stringify(x).length;
//output to console
console.log(y);
//test the length
if (y <= 700) {
pm.test("Response is BELOW 700 char");
} else {
pm.test("Response is ABOVE 700 char");
}
Thank you for another answer, does it actually count a quantity of special symbols or just symbols at all?
Not sure I follow the question, could you be more specific?
The original post said “Check that the number of characters” … are you checking only for certain characters?
Hello. The task in postman in test cases. When i send get request with my url. The whole task is:Check that the number of characters “\” (backslash) in the body of the response does not exceed (less than or equal to) 700.
If there are no such characters in the response body, then we are looking for “/” (slash)
I guess some additional cycle need to be added
You could try something like;
var stringsearch = "\\", str = pm.response.text();
for(var i=count=0; i<str.length; count+=+(stringsearch===str[i++]));
console.log(count);
if (count <= 700) {
var stringsearch = "/", str = pm.response.text();
for(var i=count=0; i<str.length; count+=+(stringsearch===str[i++]));
console.log(count);
}
There is probably a cleaner way but I’m fairly new to JavaScript.
Hello . I see some result in console but can’t really understand it. In this code possible to add some text? like if there are backslashes (<700) - such text… if no backslashes we look for usual slashes and text for this case?
Just add
console.log("There are less than 700 backslashes");
Or something similar
thanks for helping me