Validating specific type of data and not to include

Hi,

Can someone help me on a pm.test script where i need to make sure all the cars “Models = BMW” and nothing else

There is a lot of data in the response

Cars": [
{
“Model”: “BMW”,
“Colour”: “White”,
“Fuel”: “Diesel”

If the car is a different model the test should fail.

Please can someone help me on this, Thanks.

Hi @u-hussain

Try this;

const response = pm.response.json();

pm.test('Check all cars have the Model - BMW', function () {
    for(let i = 0; i < response.Cars.length; i++){
        pm.expect(response.Cars[i]).to.have.property("Model", "BMW");
    }
});
1 Like

Another option is to use the JavaScript find function to search for cars that are not equal to “BMW”.

If none are found, it should return an undefined variable so you can assert on that.

Find will only return the first record it finds.

var dataset1 = {
    "Cars": [
        {
            "Model": "BMW",
            "Colour": "White",
            "Fuel": "Diesel"
        },
         {
            "Model": "BMW",
            "Colour": "Red",
            "Fuel": "Petrol"
        },
        {
            "Model": "BMW",
            "Colour": "White",
            "Fuel": "Petrol"
        }               
    ]
};

var dataset2 = {
    "Cars": [
        {
            "Model": "BMW",
            "Colour": "White",
            "Fuel": "Diesel"
        },
         {
            "Model": "BMW",
            "Colour": "Red",
            "Fuel": "Petrol"
        },
        {
            "Model": "FORD",
            "Colour": "White",
            "Fuel": "Petrol"
        }               
    ]
};

pm.test("Dataset1 - Cars not equal to BMW = 0", () => { // Test should pass as the find should not produce any results.
    var Search = (dataset1.Cars.find(cars => {return cars.Model !== 'BMW'}));
    console.log(Search);
    pm.expect(Search).to.be.an('undefined');
});

pm.test("Dataset1 - Cars not equal to BMW = 0", () => { // test should fail as the search should find the Ford
    var Search = (dataset2.Cars.find(cars => {return cars.Model !== 'BMW'}));
    console.log(Search);
    pm.expect(Search).to.be.an('undefined');
});
1 Like