简体   繁体   中英

How can I use multiple pm.expect in one pm.test in postman tests

I want to check if request has a string then response has to contain this string in postman. I write a test like this but it doesn't work for me. I'm not sure I can use multiple pm.expect in one test with condition. My code is

pm.test("test",function(){
var hasA = data.hasOwnProperty('A');
var hasB = data.hasOwnProperty('B');
if(hasA === true){
        pm.expect(response.A).to.eql(data.A);      
}
if(hasB === true){
        pm.expect(response.B).to.eql(data.B);      
}});

Request can contain A and B both so I cannot use if..else statement. When I run this test if hasA flag true then code doesnt go into for second if even hasB option is true. How can I handle this problem.Can anyone help?

expect is hard assertion so if one fails then it won't goto next one so you can use any of the below approach:

try if conditions like:

pm.test("test", function () {

    var hasA = data.hasOwnProperty('A');
    var hasB = data.hasOwnProperty('B');
    var hasBoth = hasA && hasB
    if (hasBoth) {
        pm.expect([response.A, response.B]).to.eql([data.A, data.B]);
    } else if (hasA) {
        pm.expect(response.A).to.eql(data.A);
    } else if (hasB){
        pm.expect(response.B).to.eql(data.B);
    }
});

or

try catch like:

pm.test("test", function () {

    var hasA = data.hasOwnProperty('A');
    var hasB = data.hasOwnProperty('B');
    let error = {};
    try {
        if (hasA) {
            pm.expect(response.A).to.eql(data.A);
        }
    } catch (e) {
        error.A = e
    }
    try {
        if (hasB) {
            pm.expect(response.A).to.eql(data.A);
        }
    } catch (e) {
        error.B = e
    }

    if(Object.keys(error).length){
        pm.expect.fail(JSON.stringify(error))
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM