How to write a postman test to compare the response json against another json?

后端 未结 6 1527
闹比i
闹比i 2021-01-06 12:41

I have the below json response after running a postMan test of a Rest API:

    {
    \"glossary\": {
        \"title\": \"example glossary\",
        \"Gloss         


        
6条回答
  •  情书的邮戳
    2021-01-06 13:32

    You can paste this code into your collection or single request tests tab.

    What this code do is to save the request into a global variable with a key for that request. You can change your enviroment and hit the same request and if the response are different the test will fail.

    const responseKey = [pm.info.requestName, 'response'].join('/');
    let res = '';
    try {
        res = JSON.stringify(pm.response.json());
    } catch(e) {
        res = pm.response.text();
    }
    
    if (!pm.globals.has(responseKey)) {
        pm.globals.set(responseKey, res);
    } else {    
        pm.test(responseKey, function () {
            const response = pm.globals.get(responseKey);
            pm.globals.unset(responseKey);
            try {
                const data = pm.response.json();
                pm.expect(JSON.stringify(data)).to.eql(response);
            } catch(e) {
                const data = pm.response.text();
                pm.expect(data).to.eql(response);
            }
        });
    }
    

    Hope this help.

提交回复
热议问题