Scripts and tests

Each request can carry two small JavaScript scripts: one that runs before the request is sent, and one that runs after the response arrives. Use them to prepare data, check responses with tests and pass values from one request to the next.

A request with a post response script and its passing tests. A request with a post response script and its passing tests.

Where scripts live

Write them in the Pre-request and Post-response tabs of the request editor. In the file they are the ::: pre and ::: post sections, so they are versioned and reviewed with the rest of the request.

orders/create.postino
POST {{baseUrl}}/orders
Content-Type: application/json
Idempotency-Key: {{idempotencyKey}}

::: body json
{ "sku": "BOOK-42", "quantity": 1 }

::: pre
vars.set("idempotencyKey", util.uuid());

::: post
test("order created", () => {
  expect(res.status).toBe(201);
  expect(res.json()).toHaveProperty("id");
});
env.set("orderId", res.json().id);

Autocompletion

The script editors suggest what fits where the cursor is, in a menu with a short description of the highlighted entry:

  • Globals while you type a name: re offers req, and res too in a post-response script. res is never offered in a pre-request script, where it does not exist.
  • Members after a dot: req., req.headers., res., vars., env., console., util., and the matchers after expect(value). or expect(value).not.. A function shows its parameters, a property its type. Choosing a function inserts its name and the opening parenthesis, or both parentheses when it takes no arguments.
  • Variable names inside the quotes of vars.get(", vars.set(", env.get(", env.set(" and env.unset(": the active environment's, the session overrides and the names the script sets with vars.set(), each with its value, masked when it is a secret.
  • Header names inside the quotes of req.headers.get(", req.headers.set(", req.headers.remove(" and res.headers.get(".
  • Response keys in a post-response script, after res.json(). and further down the same path, such as res.json().data.items[0]., taken from the last response the tab received when its body is JSON of up to 20 MB. A variable assigned from it works the same: after const body = res.json();, body. offers the same keys. A key that is not a plain name is inserted as ["a-key"]. Send the request once to get them.

Nothing is suggested inside comments or other strings. The menu opens by itself while you type, and Ctrl Space opens it on demand, listing every global on an empty line. ↑ and ↓ move through it, Enter or Tab inserts the highlighted entry and Esc closes it.

Editing shortcuts

Besides the usual editing keys (see text editing), Ctrl D (⌘ D on macOS) duplicates the line under the cursor, or every line a selection touches, and Ctrl Alt D (⌘ Option D) deletes them. Both are also in the right-click menu, as Duplicate line and Delete line, and Ctrl Z undoes them in one step. The script editors also have the find bar (Ctrl F) and folding.

When they run

  1. The pre-request script runs first. It sees the request before variables are replaced, and can change its method, URL, headers and body, and set variables with vars.set().
  2. Postino replaces the {{ }} markers, applies the Auth tab and sends the request.
  3. The post-response script runs with the response in res and the request as it was actually sent in req. It runs tests and can store values for later requests with env.set().

An empty script is skipped. An error in the pre-request script stops the run before anything is sent. An error in the post-response script is reported, but the response and the tests that already ran are still shown.

Writing tests

A test is a name and a function. Inside it, expect(value) gives you matchers that throw when the check fails:

test("status is 2xx", () => {
  expect(res.status).toBeGreaterThan(199);
  expect(res.status).toBeLessThan(300);
});

test("returns a list of books", () => {
  const body = res.json();
  expect(Array.isArray(body.items)).toBe(true);
  expect(body.items.length).toBeGreaterThan(0);
});

test("first book has the expected shape", () => {
  const book = res.json().items[0];
  expect(book).toHaveProperty("isbn");
  expect(book.title).toMatch(/\w+/);
  expect(book.tags).toContain("fiction");
});

test("is JSON", () => {
  expect(res.headers.get("content-type")).toContain("application/json");
});

test("is fast enough", () => {
  expect(res.timeMs).toBeLessThan(500);
});

Every matcher can be negated with .not: expect(res.status).not.toBe(500). The full list is in the Script API.

  • A failing test records its error message and the script goes on, so one failure never hides the others.
  • Results appear in the Tests tab of the response, with a passed/total count.
  • A test can contain several expect() calls. The first one that fails ends that test.
  • Throwing your own error also fails a test: throw new Error("missing cursor").

Common recipes

Log in once, reuse the token

Store the token in the session from the login request, and reference it in every other request.

auth/login.postino
POST {{baseUrl}}/auth/login
Content-Type: application/json

::: body json
{ "username": "{{username}}", "password": "{{password}}" }

::: post
test("login succeeded", () => {
  expect(res.status).toBe(200);
});
env.set("token", res.json().token);
orders/list.postino
GET {{baseUrl}}/orders
Authorization: Bearer {{token}}

Session variables last until you quit Postino and are never written to disk, so the token does not end up in git.

Chain requests

Save an id from one response and use it in the URL of the next:

// post-response of orders/create
env.set("orderId", res.json().id);
orders/get.postino
GET {{baseUrl}}/orders/{{orderId}}
Authorization: Bearer {{token}}

Add a computed header

// pre-request
req.headers.set("X-Timestamp", String(util.now()));
req.headers.set("X-Nonce", util.randomString(16));

Build a body from code

The body must exist in the file (any type), then the script can replace its text:

// pre-request, with a ::: body json section in the file
const items = [];
for (let i = 1; i <= 3; i++) {
  items.push({ sku: "SKU-" + i, quantity: util.randomInt(1, 5) });
}
req.body = JSON.stringify({ items: items, createdAt: util.isoDate() });
// post-response of the login request
const cookie = res.headers.get("Set-Cookie");
if (cookie) {
  env.set("session", cookie.split(";")[0]);
}

Then send Cookie: {{session}} in later requests.

Fall back to a default value

// pre-request
if (!env.get("pageSize")) {
  vars.set("pageSize", "20");
}

Then {{pageSize}} uses the environment value when there is one, and 20 otherwise. env.get() reads the session variables and the active environment's files, in that order; see the Script API.

Debug a script

Print anything with console.log(). The output appears in the Console tab of the response, from both scripts:

console.log("sending", req.method, req.url);
console.log("headers", req.headers.get("Authorization") ? "with auth" : "without auth");

The sandbox

Scripts run in QuickJS, a small JavaScript engine with modern syntax: const, arrow functions, template literals, destructuring, classes, JSON, Math, Date, regular expressions and the rest of standard ECMAScript.

The sandbox has no network, file system, timers, modules, require, import, fetch, setTimeout or crypto. A script cannot send another request; to chain requests, run them one after the other and pass values with env.set().

LimitValue
Memory32 MiB per script run
Time5 seconds per script run
StateA fresh engine for every run. Nothing carries over from one run to the next except what you store with env.set().

The pre-request and post-response scripts each have their own budget. Going over a limit is reported as a script error and never crashes the app.

Moving scripts from Postman

When you import a Postman collection, request scripts are converted with this table. What has no equivalent stays as a comment, under the line // Imported from Postman. What could not be converted is commented out below.

PostmanPostino
pm.test(name, fn)test(name, fn)
pm.expect(a).to.equal(b)expect(a).toBe(b)
pm.expect(a).to.eql(b)expect(a).toEqual(b)
pm.expect(a).to.include(b)expect(a).toContain(b)
pm.expect(a).to.have.property(p)expect(a).toHaveProperty(p)
pm.expect(a).to.be.above(b)expect(a).toBeGreaterThan(b)
pm.expect(a).to.be.below(b)expect(a).toBeLessThan(b)
pm.expect(a).to.match(r)expect(a).toMatch(r)
pm.expect(a).to.be.true, false, nullexpect(a).toBe(true), and so on
pm.expect(a).to.not.equal(b)expect(a).not.toBe(b)
pm.response.to.have.status(200)expect(res.status).toBe(200)
pm.response.to.be.okexpect(res.status).toBeLessThan(300)
pm.response.coderes.status
pm.response.json()res.json()
pm.response.text()res.body
pm.response.headers.get(name)res.headers.get(name)
pm.response.responseTimeres.timeMs
pm.environment.set(k, v), pm.collectionVariables.set, pm.globals.setenv.set(k, v) (session only)
pm.environment.get(k), pm.collectionVariables.get, pm.globals.getenv.get(k)
pm.environment.unset(k)env.unset(k)
pm.variables.get(k)(vars.get(k) ?? env.get(k))
pm.variables.set(k, v)vars.set(k, v)
pm.request.headers.add({ key, value })req.headers.set(key, value)
pm.request.url, pm.request.methodreq.url, req.method
pm.sendRequest(...)Not available. Use a separate request.
CryptoJS, require(...)Not available.

Scripts attached to a Postman collection or folder are not imported, since Postino scripts belong to one request. The import lists each one it skipped.

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

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