How do I verify response values in Postman tests when the input parameter may be empty and can have multiple possible values?

In my program, there is an input parameter known as IsFruit that can have a value of either 0 or 1. If IsFruit is set to 0, the response should return fruits with a FruitsYN value of N. Similarly, if it is set to 1, FruitsYN should be Y. In cases where IsFruit has no value specified, the response can contain FruitsYN as either Y or N. I have noticed that while some test cases are passing successfully, others are failing. When I print IsFruit in cases where it is empty, it appears as ∅

var requestData = JSON.parse(request.data);
var responseData = JSON.parse(responseBody);
var IsFruit=requestData.IsFruit;// IsFruit can be either 0,1 or empty
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
    pm.test("Check if Fruits found with this search criteria", function() {
        pm.expect(responseData.Message).to.not.eql("No Fruits found with this search criteria");

        var list = (responseData.Fruits).length;
        //console.log(list);
        var a = [];
        
        for (var i = 0; i < list; i++) {
            var counter = responseData.Fruits[i];
            FruitsYN = counter.FruitsYN
            //console.log(FruitsYN);
            a.push(FruitsYN)
            pm.test("Check whether Fruit values in the Fruits returned is accurate based on fruit filter in the request", function() {

                if (IsFruit == 0) {

                    pm.expect(FruitsYN).to.eql("N")

                }
                if (IsFruit == 1) {
                    pm.expect(FruitsYN).to.eql("Y")
                }

                if (IsFruit =="") {
                    pm.expect(FruitsYN).to.be.oneOf(["Y", "N"]);
                }
            });
        }
    });
});

Answer №1

It seems that variable names starting with uppercase characters are not functioning properly in Postman.

The following code snippet is working for me:

let requestData = {"IsFruit":""};
let isFruit=requestData.IsFruit;// IsFruit can be either 0,1 or empty

if (isFruit =="") {
    console.log("Empty string");
}

However, using IsFruit does not work as expected.

Answer №2

After some troubleshooting, I successfully resolved the issue by implementing a new if condition. It turns out that the problem stemmed from a null value, which I addressed by adding the following code snippet:

if (isFruit == "") { isFruit = "empty"; }
I then utilized this updated variable in another conditional statement as shown below:
if (isFruit == "empty") { pm.expect(FruitYN).to.be.oneOf(["Y", "N"]); }

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

What is the best way to assign or convert an object of one type to another specific type?

So here's the scenario: I have an object of type 'any' and I want to assign it an object of type 'myResponse' as shown below. public obj: any; public set Result() { obj = myResponse; } Now, in another function ...

Designing a Dynamic Floating Element that Shifts with Scroll Movement

Hey there everyone!, I am currently working on a project in Wordpress and I was wondering if anyone has experience creating a floating widget that moves along with the page as you scroll. Any suggestions on how to achieve this? Would it involve using Javas ...

Duplicating labels with JavaScript

I need assistance with copying HTML to my clipboard. The issue I am encountering is that when I try to copy the button inside the tagHolder, it ends up copying <span style="font-family: Arial; font-size: 13.3333px; text-align: center; background-color: ...

Transforming the string attribute of an object within a JavaScript array through mapping

Here is an array of objects: { "attr1": 123, "attr2": "a.end", }, { "attr1": 123, "attr2": "b.start", } The task is to remove the first part of the attr2 string up to and including the '.& ...

Make sure to verify if the mode in Angular is either visible-print or hidden-print

Here is a snippet of code <div class="row"> <div class="col-sm-12 visible-print"> Content (display in full width when printed) </div> <div class="col-sm-6 hidden-print"> Content (same as above but only half width when ...

Filter out JSON array fields based on specific values

Suppose I need to extract a CSV with specific fields from a large json file produced by an API... all relevant data is contained within an array. jq -r ".array[] | [.uniqV,.V1,.V2,.V3] | @csv" something.json ... but if the unique value begins with a part ...

Having trouble with expressJs router.post() not functioning properly with multiple middleware, resulting in an [object Undefined] error

I have been working on developing a REST API for my users, utilizing express-validator for validation before adding the user to the database. However, I encountered an issue while chaining my middleware in the router.py file which resulted in the error Err ...

Example of a simple router template without URL access

I am currently working on a basic example of react router with two simple routes, greetings and signup, set up within a template. Everything seems to be loading fine without any errors, but when I manually enter the /signup route in the address bar, I enco ...

Is there a way to search through an array of object arrays in JavaScript for a specific key/value pair using lodash or any other function?

I am faced with a task involving an array of objects. Each object has a key that needs to be used to search through sets of arrays containing similar objects. The goal is to determine if all the arrays contain the same value for a specific key in my object ...

What is the best way to assign attributes to all items in an array, excluding the currently selected one?

I need to implement dynamic buttons in my HTML document while a JavaScript class is running and receives a response from the backend. I am using jQuery and vanilla JS, and have included an example below to demonstrate this functionality. The goal is to dis ...

Which event occurs first for a4j:jsFunction, reRender or oncomplete?

After running a jsFunction, I want the javascript to execute once the re-rendering is completed. I assume that the "oncomplete" javascript function is triggered after the re-rendering process, but I'm not entirely certain. Any insights on this? Appre ...

Using json_encode with chart.js will not produce the desired result

I am attempting to utilize chart.js (newest version) to generate a pie chart. I have constructed an array that I intend to use as the data input for the chart. This is the PHP code snippet: <?php if($os != null) { $tiposOs = array('Orçamento ...

Tips for incorporating conditional statements within return statements in functional components in React JS

I need to display the login page if the user is not logged in, otherwise show the forbidden 403 page. Since I'm using a functional component, I can't use render(). return forbidden === false ? ( <> <Container maxWidth="x ...

Using Jersey to successfully bind JSON data to intricate Java classes

As I develop my RESTful API with Jersey, the use of JSON is essential. I am aware that Jersey relies on Jackson for automatically binding JSON to Java classes. However, I find myself a bit confused about the dependencies involved in this process. It appear ...

Dirty context detected in Material-UI TextField

Trying to understand how to check for dirtyness with material-ui's FormControl or TextField component. The TextField demo page mentions that TextField is made up of smaller components (FormControl, InputLabel, Input, and FormHelperText) which can be c ...

Tips for reducing the size of your JavaScript buffer

Is it the correct way to convert a buffer to a string, trim it, and then convert back to a buffer in Node.js v6.12.x? var buf = Buffer.alloc(xxxxxx); ..... // buffer receives its value ..... let buffParsed = String.fromCharCode.apply(null, buf); buffPa ...

Adding properties to Vue.js component in the script section without affecting rendering

How can I import component A with props and pass it to another component B for rendering? import MyComponent from '/MyComponent.vue' computed: { compnt: function () { var comp = MyComponent // How can I set props to MyC ...

What is the method for executing PHP code without the need for users to access the webpage?

Similar Query: Optimal method for running a PHP script on a schedule? I am in need of a solution where a PHP script can consistently fetch data from a single website, store it in a database on the server, and then update multiple other websites. The c ...

`In TypeScript Angular, encountering challenges with accessing object properties`

My TypeScript object looks like this const playlist: { tracks: Array<Track> } = { tracks: new Array<Track>() }; This is the Track interface I am working with interface Track { title?: string; album?: string; artists?: string; duration? ...

Luxon DateTime TS Error: The 'DateTime' namespace cannot be used as a type in this context

I have encountered an issue while trying to set the type of a luxon 'DateTime' object in TypeScript. The error message DateTime: Cannot use namespace 'DateTime' as a type appears every time I attempt to assign DateTime as a type. Below ...