- Introduce The Question:
I am trying to create an off-line script file from a command that includes tests and a pre-request script, to toggle a network-conneted light on and off. I used a pre-built command from another user here, and it works perfectly inside Postman itself.
The issue is I can’t work out how to export it to run offline, as a powershell script or anything else.
I’ve managed to get a simpler version of this code, that just sends an “ON” or “OFF” command, to work using the Postman’s Code Snippet function (Powershell:Restmethod), but I’m a complete n00b and so don’t know how to write a full script that does the tests and parses the response to send the correct command.
- Additional Data
PUT 192.168.1.178:9123/elgato/lights
BODY:
{
"lights": [
{
"on": {{light_on_updated}}
}
]
}
PRE-REQUEST SCRIPT
// If collection variable is not already set, defined a default value
if(pm.collectionVariables.get("light_on") === undefined) {
pm.collectionVariables.set("light_on", 0);
}
//Defining updated value
pm.variables.set("light_on_updated", +!pm.collectionVariables.get("light_on"));
TEST
// Testing request didn't failed
pm.test("Request didn't failed", function () {
pm.response.to.have.status(200);
});
// Testing light has been turned on or off as expected
const lightOnLabels = ["off", "on"]; // off is 0 and on is 1
const lightOnExpected = pm.variables.get("light_on_updated"); // Retrieving local variable
const lightOnExpectedLabel = lightOnLabels[lightOnExpected]; // Using on value as index to get label
pm.test("Light has been turned " + lightOnExpectedLabel, function () {
// Checking new on value matches the expected one
const lightOn = pm.response.json().lights[0].on
pm.expect(lightOn).to.eql(lightOnExpected);
// Storing on value for next call
pm.collectionVariables.set("light_on", lightOn);
});