Postman 脚本:循环中只执行最后一个请求,为什么?

问题描述 投票:0回答:2

为什么会发生这种情况,只有最后的请求才被执行。 预请求脚本:

const testCases = ['1002', '3002', '100002', 'singh', '1002y'];

    // Set the productid variable for the current iteration
    pm.variables.set('productid', testCases[3]);
    pm.sendRequest({
        url: pm.variables.replaceIn("{{baseUrl}}/products/:priductId"),
        method: 'GET'
    });

    pm.variables.set('productid', testCases[0]);
    pm.sendRequest({
        url: pm.variables.replaceIn("{{baseUrl}}/products/:priductId"),
        method: 'GET'
    });

测试:

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
    if(pm.response.code === 200)
    console.log("ok");
});

pm.test("Status code is 400", function () {
    pm.expect(pm.response.code).to.equal(400);
        if(pm.response.code === 400)
    console.log("Bad Response");
});
console:
 
GET https://valentinos-coffee.herokuapp.com/products/:priductId
400
271 ms
 
GET https://valentinos-coffee.herokuapp.com/products/:priductId
400
275 ms
 
GET https://valentinos-coffee.herokuapp.com/products/1002
200
269 ms
 
ok

在这段代码中也发生了同样的事情

const testCases = ['1002', '3002', '100002', 'singh', '1002y'];

// Loop through test cases
for (let i = 0; i < testCases.length; i++) {
    // Set the productid variable for the current iteration
    pm.variables.set('productid', testCases[i]);

    // Make the API request
    const response = pm.sendRequest({
        url: pm.variables.replaceIn("{{baseUrl}}/products/:productId"),
        method: 'GET'
    });
}

正如你从控制台看到的,最后才分配了productid, 也尝试过承诺,然后只有一个请求发出, 尝试添加人工等待以使其等待 3 秒,然后同样的事情也发生,只有最后的请求分配了productid。

我想纠正它,以便每个请求都有一个测试输出,然后下一个请求就像那样

javascript postman postman-pre-request-script
2个回答
1
投票

每个

pm.sendRequest
都是一个异步操作,不会阻塞后续代码的执行。因此,当您循环测试用例并设置
productid
变量时,循环不会等待每个请求完成才继续进行下一次迭代。这会导致仅使用预期的
productid
执行最后一个请求,因为循环已完成其执行,并在任何请求有机会启动之前将
productid
设置为
testCases
数组中的最后一项。

此外,在您的预请求脚本中,URL 参数名称中存在拼写错误(

:priductId
应为
:productId
),这可能会导致请求无法按预期工作。

要纠正该问题并确保每个请求都以其相应的

productid
执行,您可以使用 JavaScript 的异步/等待模式以及 Postman 的沙箱环境处理异步操作的能力。以下是您可以修改循环以等待每个请求完成然后再继续下一个请求的方法:

(async () => {
    const testCases = ['1002', '3002', '100002', 'singh', '1002y'];

    for (let i = 0; i < testCases.length; i++) {
        pm.variables.set('productid', testCases[i]);
        
        const url = pm.variables.replaceIn("{{baseUrl}}/products/" + testCases[i]); // Correct the URL substitution
        await new Promise((resolve, reject) => {
            pm.sendRequest(url, {method: 'GET'}, (err, response) => {
                if (err) {
                    console.log(err);
                    reject(err);
                } else {
                    console.log(`Request for productid ${testCases[i]} completed with status ${response.code}`);
                    resolve(response);
                }
            });
        });
    }
})();

0
投票

使用

Run collection

这将使循环API调用变得容易

另存为

1-demo-collection.json
文件

{
    "info": {
        "_postman_id": "b0791408-a367-47c1-a96c-3b305a634c10",
        "name": "1-demo",
        "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
        "_exporter_id": "1826150"
    },
    "item": [
        {
            "name": "Get Coffee",
            "event": [
                {
                    "listen": "test",
                    "script": {
                        "exec": [
                            "const jsonData = pm.response.json();",
                            "",
                            "console.log(\"priductIds: \" + pm.collectionVariables.get(\"priductIds\"));",
                            "console.log(\"name: \" + jsonData.name);",
                            "",
                            "let priductIds = JSON.parse(pm.collectionVariables.get(\"priductIds\"));",
                            "if (priductIds.length > 0){",
                            "    postman.setNextRequest(\"Get Coffee\");",
                            "}",
                            "",
                            "pm.test('Status code should be 200 :  ' + pm.response.code, function () {",
                            "    pm.expect(pm.response.code).to.equal(200);",
                            "});",
                            ""
                        ],
                        "type": "text/javascript"
                    }
                },
                {
                    "listen": "prerequest",
                    "script": {
                        "exec": [
                            "let priductIds = JSON.parse(pm.collectionVariables.get(\"priductIds\"));",
                            "console.log(priductIds);",
                            "pm.collectionVariables.set(\"priductId\", priductIds.shift())",
                            "pm.collectionVariables.set(\"priductIds\", JSON.stringify(priductIds));"
                        ],
                        "type": "text/javascript"
                    }
                }
            ],
            "request": {
                "auth": {
                    "type": "noauth"
                },
                "method": "GET",
                "header": [],
                "url": {
                    "raw": "{{baseUrl}}/products/{{priductId}}",
                    "host": [
                        "{{baseUrl}}"
                    ],
                    "path": [
                        "products",
                        "{{priductId}}"
                    ]
                }
            },
            "response": []
        }
    ],
    "event": [
        {
            "listen": "prerequest",
            "script": {
                "type": "text/javascript",
                "exec": [
                    ""
                ]
            }
        },
        {
            "listen": "test",
            "script": {
                "type": "text/javascript",
                "exec": [
                    ""
                ]
            }
        }
    ],
    "variable": [
        {
            "key": "priductIds",
            "value": "[\"1001\", \"1002\", \"1003\", \"1004\", \"3002\"]",
            "type": "string"
        },
        {
            "key": "priductId",
            "value": "1001",
            "type": "string"
        },
        {
            "key": "baseUrl",
            "value": "https://valentinos-coffee.herokuapp.com",
            "type": "string"
        }
    ]
}

Import collection

Collection Variable

URL

GET {{baseUrl}}/products/{{priductId}}

Pre-request Script

let priductIds = JSON.parse(pm.collectionVariables.get("priductIds"));
console.log(priductIds);
pm.collectionVariables.set("priductId", priductIds.shift())
pm.collectionVariables.set("priductIds", JSON.stringify(priductIds));

Tests Script

const jsonData = pm.response.json();

console.log("priductIds: " + pm.collectionVariables.get("priductIds"));
console.log("name: " + jsonData.name);

let priductIds = JSON.parse(pm.collectionVariables.get("priductIds"));
if (priductIds.length > 0){
    postman.setNextRequest("Get Coffee");
}

pm.test('Status code should be 200 :  ' + pm.response.code, function () {
    pm.expect(pm.response.code).to.equal(200);
});

Run it

Result

© www.soinside.com 2019 - 2024. All rights reserved.