Script API

The complete list of globals available to ::: pre and ::: post scripts, with their exact behavior. For a gentler introduction, read Scripts and tests first. The script editors suggest these globals and their members as you type, see autocompletion.

GlobalPre-requestPost-responsePurpose
reqRead and writeRead onlyThe request
resNot definedRead onlyThe response
varsRead and writeRead and writeVariables of this run
envRead and writeRead and writeSession and environment variables
testYesYesRecord a test
expectYesYesAssertions
consoleYesYesOutput to the Console tab
utilYesYesUUIDs, time, random values, encoders

req

The request. In a pre-request script it is the request about to be sent, before {{ }} markers are replaced. In a post-response script it is the request exactly as it was sent: variables replaced, query string appended and automatic Content-Type included.

MemberTypeDescription
req.methodstringThe method, such as "GET".
req.urlstringThe URL.
req.bodystringThe body text. A form body reads as key=value&key2=value2, not yet percent-encoded. A request without a body reads as "".
req.headers.get(name)string or undefinedThe value of the first enabled header with that name, ignoring case.
req.headers.set(name, value)Replaces the value of the header with that name (ignoring case, keeping its original spelling), or adds it.
req.headers.remove(name)Removes every enabled header with that name, ignoring case.
  • In a pre-request script, assigning req.method, req.url or req.body changes what is sent. Values are converted with String(value).
  • Assigning req.body on a request whose file has no body section has no effect: the script cannot choose a body type. Add an empty ::: body json (or another type) to the file first.
  • Disabled headers are invisible to the script and are kept unchanged in the request.
  • Query parameters, scripts and docs are not visible to scripts. To change a query parameter, edit req.url.
  • The Auth tab is applied after the pre-request script, so the header or parameter it adds is not in req there, and variables the script sets with vars.set() reach its fields. The post-response script sees it in req, as it was sent.
  • In a post-response script, every write throws, for example req.url is read-only in a post script or headers are read-only in a post script.

res

The response. Defined only in post-response scripts.

MemberTypeDescription
res.statusnumberThe status code, such as 200.
res.headers.get(name)string or undefinedThe value of the first header with that name, ignoring case. set and remove throw.
res.bodystringThe body as text, decoded as UTF-8. Invalid bytes are replaced.
res.json()anyJSON.parse(res.body). Throws if the body is not valid JSON.
res.timeMsnumberTotal time in milliseconds, from opening the connection to reading the last byte.
res.sizenumberBody size in bytes.
Tip

res.json() parses the body on every call. In a script that reads many fields, parse once: const body = res.json();

vars

Variables that live for one run of one request. They have the highest priority when {{ }} markers are replaced.

MemberDescription
vars.get(name)The value, or undefined. Names are case sensitive.
vars.set(name, value)Sets a variable. The value is converted with String(value).

Variables set in the pre-request script are used to fill the request and are readable in the post-response script of the same run. They are never written to disk and no other request sees them. There is no vars.unset.

env

The session environment: variables set by scripts since Postino started, on top of the active environment's files.

MemberDescription
env.get(name)The session value if a script set one, otherwise the value from the active environment (.local.env over .env), as written in the file, without expanding the variables it refers to, otherwise undefined. Names are case sensitive.
env.set(name, value)Sets a session variable. The value is converted with String(value).
env.unset(name)Removes the session variable, so the value from the environment files, if any, applies again.
  • Changes are applied after the script finishes, in the order they were made. They are visible to every later request until you quit Postino.
  • They are never written to an .env file. The environment editor lists them as session.
  • In a load test, each virtual user has its own copy of the session, so a token set by one user's login is used by that same user's next requests.

test(name, fn)

Runs fn right away. If it returns, the test passes. If it throws, the test fails with the error's message (or String(error) when something other than an Error is thrown). Either way the script continues with the next statement.

test("has a next page cursor", () => {
  const cursor = res.json().next;
  if (!cursor) {
    throw new Error("no cursor in the response");
  }
  env.set("cursor", cursor);
});

Tests are synchronous. A function that returns a promise is considered passed when it returns.

expect(value)

Returns a set of matchers. A matcher throws when its condition does not hold, which fails the surrounding test(). expect(value).not returns the same matchers with the condition inverted.

MatcherPasses whenFailure message
toBe(expected)value === expectedexpected 404 to be 200
toEqual(expected)JSON.stringify(value) === JSON.stringify(expected)expected {"a":1} to equal {"a":2}
toBeTruthy()Boolean(value) is trueexpected "" to be truthy
toBeFalsy()!value is trueexpected 1 to be falsy
toContain(item)value is a string containing item, or an array containing it (===)expected "abc" to contain "z". Throws toContain needs a string or an array for other types.
toMatch(pattern)String(value) matches the regular expression, or the string turned into oneexpected "x" to match /\d+/
toBeGreaterThan(n)value > nexpected 3 to be greater than 5
toBeLessThan(n)value < nexpected 900 to be less than 500
toHaveProperty(name)value has an own property nameexpected {} to have property "id"

With .not, the message includes the word not: expected 200 not to be 200.

Note

toEqual compares JSON text, so the order of keys matters: {a: 1, b: 2} does not equal {b: 2, a: 1}. Compare fields one by one when the order is not guaranteed.

console

console.log(), console.info(), console.warn() and console.error() each add one line to the Console tab, tagged with the level, the time and the script line of the call. Arguments are joined with a space; strings are printed as they are, anything else with JSON.stringify, falling back to String(value).

util

The template functions, callable from code. Same implementation, same results, same error messages.

FunctionReturns
util.uuid()string, a random UUID v4
util.now()number, milliseconds since the Unix epoch
util.isoDate()string, the current UTC time in RFC 3339
util.randomInt(min, max)number, an integer between min and max, both included
util.randomString(len)string of letters and digits, at most 1,048,576 characters. Throws on a longer or negative length
util.base64Encode(str)string
util.base64Decode(str)string. Throws on invalid Base64 or non UTF-8 output
util.urlEncode(str)string, percent-encoded

A bad call, such as an unknown function, the wrong number of arguments or the wrong type, throws an Error.

Execution rules

RuleDetail
EngineQuickJS, standard ECMAScript.
IsolationA new runtime for every script run. Nothing survives between runs except env changes.
Not availableNetwork, files, timers, modules, require, import, fetch, setTimeout, crypto.
Memory32 MiB per run.
Time5 seconds per run.
Empty scriptSkipped without starting the engine.
Error in pre-requestThe run stops. Nothing is sent.
Error in post-responseReported. The response, the tests and the console lines produced so far are kept.

Found a mistake? Edit this page on GitHub or open an issue.

↑↓to move ↵to open /or Ctrl Kto search from any page