Pre-Request Script

You are here:
< All Topics

Pre-request scripts is a piece of code that will run before the execution of a request.

We can use the pre-request script for a pre-processing task such as:

  • Setting parameters, headers
  • Adding body data
  • Adding variable values
  • Including timestamps in request headers etc…

A special pw API object contains various methods for creating Scripts and tests and is made available globally. It can be referenced by name to access methods such as pw.env.set().

pw.env.set() can be used directly for quick and convenient environment variables definition. 

For Ex. 

pw.env.set("baseURL", "https:/");
pw.env.set("method", "get");

To access these newly set variables use “<<<variable_name>>>”

Consider the following example of Pre-request Scripts:

var random = Math.floor(Math.random() * 10);
pw.env.set("randomValue", random);

Above Pre-request Scripts will generate a random number & will set its value to “randomValue” variable. To use that variable, we simply need to add “<<<randomValue>>>” to the endpoint URL.

Table of Contents