SpitfireLoad Testing & APMWhat's new

Script step (JavaScript)

The built-in extractors and checks cover most tests. When you need to work out a value, sign a request or check the answer with a rule of your own, you can write JavaScript in the test editor. There are two ways:

  • Script step: Script (JavaScript) in the protocol list. It sends no request; the code reads, works out and writes the VU's variables. Later steps use what it writes as {{name}}.
  • Before / After script: on every step's Script tab. The before script runs before the request (in HTTP it can change the request), the after script runs after the answer and the extractors.

Scripts are on in every edition (Free included); there is no license limit. Running k6 scripts as they are is a different path: see External engines.

Adding a script step

  1. In the test editor press Add step.
  2. On the step card pick Script (JavaScript) in the Protocol list. An example opens in the box.
  3. Write the code. Line numbers show on the left; Tab inserts two spaces.
  4. Press Try under the code, then Run. The script runs in the sandbox with sample values and shows the changed variables, checks and log lines. No request is sent.
  5. You can tell it worked: it says "The script finished without errors" and the variable you wrote shows under Changed variables.
js
// Work out the total from the previous step's answer
const cart = response.json();
const total = cart.items.reduce((t, i) => t + i.price * i.qty, 0);
vars.set('total', total.toFixed(2));
check('cart is not empty', cart.items.length > 0);

The next step gets this value with {{total}}.

Note

A script step is not a request: it does not count in the request metrics (RPS, latency). Each iteration it writes a check named script; the check fails when the script throws or calls fail(). The script's own check() calls show in the same check list.

Before and after scripts

  1. On an HTTP (or any other protocol) step open the Script tab.
  2. Switch on Before script or After script. An example comes in.
  3. Write the code and try it with Try. When trying an after script you can change the sample answer's status code and body.

A before script that signs the request:

js
const ts = String(now());
request.headers['X-Timestamp'] = ts;
request.headers['X-Signature'] = hmac('sha256', vars.get('secret_api_key'), ts + request.body);

An after script that checks the answer with your own rule:

js
const j = response.json();
check('order confirmed', j.status === 'confirmed');
if (j.total > 10000) fail('total larger than expected: ' + j.total);
vars.set('orderId', j.id);

The order is: before script → request → extractors → after script → checks. The variables the extractors write are read in the after script with vars.get().

Warning

When a before script throws or calls fail() the request is not sent and the step counts as a failed request (error:script). skip() skips the request quietly; no metrics are written.

The API

The orange i next to the code shows the same list in short.

API Meaning
vars.get(name), vars.set(name, value), vars.has(name), vars.del(name) The VU's variables. Values become text, objects become JSON.
data('users') This iteration's CSV row: {column: value} (the same as {{users.email}}).
request.method, request.url, request.headers, request.body Only in an HTTP step's before script. What you change is sent.
response.code, .status, .body, .json(), .header(name), .duration, .failed In an after script the step's answer; in a script step the previous step's answer (or null).
check(name, condition) A check result. Thresholds and reports read it. At most 50 names per step.
fail(reason) Counts the step as failed.
skip() Only in a before script: skips this step's request.
stop() Ends the iteration here.
goto('Step name') Goes on with that step next (at most 1000 jumps per iteration).
log(...), console.log(...) Writes a line to the run log; with Try it shows under the step.
uuid(), now(), randomInt(a, b), randomItem(array), randomString(n) Random and time helpers.
base64.encode/decode, hex.encode/decode Encoding.
md5(s), sha1(s), sha256(s), sha512(s), hmac(alg, key, message, 'hex' | 'base64') Hashes and HMAC (hex by default).
render('{{$uuid}}-{{id}}') The same result as the template engine ({{fake.*}} included).
__VU, __ITER The VU and iteration numbers.
pm.*, expect(...) The subset of Postman scripts: pm.environment.get/set, pm.response.json(), pm.test, pm.expect(x).to.eql(...).

The code runs inside a function: return ends it early.

Limits and safety

  • Each run gets at most 50 ms of CPU. If you need longer, set options.scriptTimeout in the JSON view, up to 1s. A script over its time is stopped and the step fails.
  • The sandbox has no network, files, processes or require. The script runs inside the runner and never blocks a service.
  • A vars.set value keeps at most 1 MiB, a log line at most 1 KiB.
  • log() writes 20 lines a minute per run per runner; the rest is dropped and the number dropped is written.
  • The source may be at most 64 KiB. Variables starting with secret_ are read with vars.get but do not appear in bulk lists such as pm.environment.toObject().

Errors

A script error shows with its line and column, for example: "The script stopped at line 3, column 5: total is not defined." It also says what to do.

Message Cause What to do
The script has a syntax error A missing bracket, quote or semicolon Fix the line given; the editor warns before saving too.
… is not defined A name that was never defined Read variables with vars.get('name').
The script did not finish within its time limit An endless or very long loop Shorten the loop or raise options.scriptTimeout.
The script counted the step as failed with fail() Your code called fail() The message is yours; check the condition.

To try the whole scenario, Try at the top of the editor runs the scripts too: under each step you see its script log lines and the error line.

Importing from Postman

The scripts of a Postman collection are first converted line by line into extractors and checks. When a script has lines that cannot be converted (e.g. console.log, your own arithmetic) the whole script comes along as it is as the step's before or after script and runs with the pm subset. The import report says "came along as a script". Scripts that use what the sandbox does not have (pm.sendRequest, setTimeout, require) are converted line by line as before; the lines left out are listed in the report.

  • Test editor: step structure, extractors, checks and Try.
  • Test data: CSV data files and passing values between steps.
  • External engines: running k6, JMeter, Gatling and Locust scripts as they are.