> For the complete documentation index, see [llms.txt](https://learning.contextqa.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://learning.contextqa.com/web-testing/custom-code-steps.md).

# Custom Code Steps

## Quick answer

How to write and execute custom JavaScript code as test steps — for complex logic, calculations, and DOM interactions that go beyond natural language steps. Use this page to understand when the capability applies, complete its user-facing workflow, and verify the expected result.

## What this page covers

{% hint style="info" %}
**Who is this for?** SDETs and developers who need to execute custom JavaScript within a test case for logic that cannot be expressed as a natural language step.
{% endhint %}

Custom code steps let you write JavaScript that executes during test runtime. Use them for complex calculations, custom data transformations, direct DOM manipulation, or any scenario where a natural language instruction is insufficient.

## Prerequisites

* You have created or opened a test case.
* You are familiar with the [Test Steps Editor](/web-testing/test-steps-editor.md) basics.
* You have working knowledge of JavaScript.

***

## Adding a custom code step

1. Open a test case and click **Add Step**.
2. In the step builder sidebar, select **Custom Code**.
3. Select **JavaScript** from the **Language** dropdown.
4. Write your code in the code editor.
5. Click **Create Step** to add the step to your test case.

***

## Fields

| Field           | Description                                                                                   |
| --------------- | --------------------------------------------------------------------------------------------- |
| **Language**    | The scripting language. Currently supports **JavaScript**.                                    |
| **Code**        | The JavaScript code to execute at runtime.                                                    |
| **Description** | A plain-English summary of what the code does. Appears in the step list and execution report. |

***

## Example: Generate a unique identifier

```javascript
// Generate a unique email for registration testing
const timestamp = Date.now();
const uniqueEmail = `testuser_${timestamp}@example.com`;
return uniqueEmail;
```

***

## Example: Calculate and verify a total

```javascript
// Calculate expected cart total from individual prices
const prices = [19.99, 24.50, 7.99];
const expectedTotal = prices.reduce((sum, price) => sum + price, 0).toFixed(2);
return expectedTotal;
// => "52.48"
```

***

## Example: Parse and transform data

```javascript
// Extract order IDs from a JSON response stored in a variable
const response = JSON.parse(context.variables.orderListResponse);
const orderIds = response.body.orders.map(order => order.id);
return orderIds.join(', ');
```

## Use an AI Ask result in custom code

An **AI Ask** action can save its answer to a runtime variable. A later Custom Code step can consume that value:

1. Add an **AI Ask** step, write a focused question, and set its output variable to a valid name such as `invoiceSummary`.
2. Place the Custom Code step after the AI Ask step.
3. Read the stored value by its exact, case-sensitive name—for example, `context.variables.invoiceSummary`.
4. Validate or parse the value before using it in a calculation or request.

```javascript
const summary = String(context.variables.invoiceSummary ?? '').trim();
if (!summary) {
  throw new Error('AI Ask did not return invoiceSummary');
}
return summary.toUpperCase();
```

AI output is generated text, so do not treat it as a trusted number, selector, command, or JSON object without validation. For an exact value already displayed in the DOM, use **Store text from the element … into variable …** instead of AI Ask.

## Calculation and assertion pattern

For a calculation such as `total = subtotal + tax`, keep capture, calculation, and verification separate:

1. Store the displayed subtotal and tax in runtime variables.
2. Use Custom Code to parse the currency strings and calculate the expected total with the application's rounding rule.
3. Store or return the calculated value using the output supported by the selected Custom Code template.
4. Add a verification step that compares the displayed total with that expected value.

For a visual, non-critical check, an AI Verification prompt can read: `Verify that the displayed Total equals Subtotal plus Tax, using two decimal places.` For payment, ledger, or settlement validation, use an exact numeric assertion or API response validation instead of relying only on visual AI reasoning.

***

## Advanced settings

| Setting              | Description                                                             |
| -------------------- | ----------------------------------------------------------------------- |
| **Skip Step**        | Skip this step during execution without removing it from the test case. |
| **Mark as Optional** | If enabled, a failure on this step does not fail the overall test case. |

***

## Tips & best practices

* **Add a descriptive Description field** so the step is understandable in the execution report without reading the code.
* **Keep code minimal.** Custom code steps are for logic that natural language steps cannot handle. If a task can be described in plain English, use an AI Agent step instead.
* **Use custom code for data transformation** between steps — formatting dates, calculating expected values, parsing complex response structures.
* **Avoid long-running operations.** The step has a default timeout of 30 seconds. If your code needs more time, increase the step timeout.

## Troubleshooting

**Custom code step fails with a syntax error** Check the browser console output in the execution report. JavaScript syntax errors surface as step failures with the error message in the step details. Validate your code in a browser console before pasting it into the step editor.

**Variables from previous steps are not accessible** Verify the variable name is spelled correctly and that the step that sets the variable runs before the custom code step. Variable names are case-sensitive.

## Related pages

* [Test Steps Editor](/web-testing/test-steps-editor.md)
* [Test Data Management](/web-testing/test-data-management.md)
* [Creating Test Cases](/web-testing/creating-test-cases.md)

{% hint style="info" %}
**70% less manual test maintenance with AI self-healing.** [**Book a Demo →**](https://contextqa.com/book-a-demo/) — See ContextQA create and maintain tests for your web application.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://learning.contextqa.com/web-testing/custom-code-steps.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
