JavaScript steps

Run code in the page with Execute Javascript, JavaScript returns true and Extract from JavaScript.

The three actions

Each action runs the JavaScript Code field in the page under test:

  • Execute Javascript: runs the code and ignores the result. Use it to scroll, clear storage or set up state
  • JavaScript returns true: passes when the code returns a truthy value and fails otherwise
  • Extract from JavaScript: saves the returned value into the variable named in Variable Name

Returning a value

The code runs as the body of a function. Use return to send a value back. Without return the result is empty, so JavaScript returns true fails and Extract from JavaScript saves an empty value.

Keep the code synchronous and return the value directly.

// JavaScript returns true
return document.querySelectorAll('.product').length >= 3;

// Extract from JavaScript, Variable Name: ORDER_ID
return document.querySelector('[data-test=order-id]').textContent.trim();

Variables in JavaScript

In JavaScript Code fields and step conditions, variable values are escaped as the inside of a JavaScript string. Quotes, backslashes and line breaks in a value cannot break the code, but you must wrap the placeholder in quotes yourself.

// Correct
return document.body.innerText.includes('{{CUSTOMER_NAME}}');

// Incorrect: the value is inserted without quotes
return document.body.innerText.includes({{CUSTOMER_NAME}});

Converting values

Because a variable is always inserted as text, convert it when you need a number.

return Number('{{EXPECTED_COUNT}}') === document.querySelectorAll('.row').length;

Errors

If the code throws, the step fails with Javascript error followed by the browser's message. Check the step error in the run result to see which line failed.