xtest

Test Automation

AI-powered Test Generation

This course explores how artificial intelligence is changing the way test cases are created, maintained and executed. Learners will move from traditional, hand-written test scripts toward workflows where a model reads an application, a specification or plain English instructions and produces runnable test steps. The course covers the underlying ideas behind AI test generation, practical techniques for writing prompts and specifications that produce reliable tests, strategies for validating and maintaining AI-generated artifacts, and how such workflows fit into a modern CI/CD pipeline. Real, publicly available tools such as Playwright are used for hands-on examples throughout, so every exercise can be reproduced outside of any single vendor's product. By the end of the course, learners will be able to evaluate when AI-assisted generation helps a test suite, write effective instructions for an AI test agent, and build a review process that keeps AI-generated tests trustworthy over time.

Intermediate · By the Xtest team · About 34 minutes to read

Introduction

Writing and maintaining automated tests by hand is one of the most time-consuming parts of a QA engineer's job. Every new feature means new scripts, every UI change means broken locators, and every release means hours spent chasing down why a once-passing test suddenly fails. AI-powered test generation offers a different way of working: instead of writing every line of a test script, a tester describes what should happen, and a model turns that description into working steps that can be run, reviewed and replayed. This course introduces the ideas behind that shift. You will learn how large language models read a page or an application, decide on actions, and translate an outcome like 'log in and add an item to the cart' into a concrete, repeatable sequence of clicks, typing and assertions. You will also learn the limits of this approach: AI-generated tests still need human review, still need a strategy for handling UI changes, and still need to fit into the rest of a team's testing practice rather than replace it. Alongside general principles, you will get hands-on practice with real, publicly available tools, including Playwright's own code generation capabilities, so that the techniques you learn apply no matter which vendor's product you end up using day to day. Along the way we will also look at how hosted platforms that combine AI agents with a live browser or device fit into this picture, using xtest as one example of that approach. By the end of this course, you will be equipped to evaluate, adopt and responsibly maintain AI-assisted test generation in your own projects.

Understanding AI-Powered Test Generation

What AI-Powered Test Generation Means

Traditional test automation requires someone to write every line of a script: find the right locator, decide the right action, add the right assertion. AI-powered test generation changes the starting point. Instead of a script, you start from an intention, expressed as plain language ('search for a product and verify it appears in results'), a specification document, or a recorded interaction, and a model turns that intention into runnable steps.

There are a few common shapes this takes in practice:

  • Natural language to test code: a tester or developer writes a sentence describing a scenario, and a model produces a script in a chosen framework.
  • Record-and-generate: a human performs the actions once, and a tool captures them into a structured test, sometimes with a model cleaning up or generalizing the result.
  • Agentic execution: rather than generating a static script up front, a model reads the current state of the page at run time and decides the next action itself, step by step, which can make the test more resilient to minor UI changes.

Why This Matters for a QA Practice

AI-generated tests do not remove the need for testing expertise. A model is only as good as the instructions and context it is given, and someone still has to decide what is worth testing, what a correct outcome looks like, and how to handle a result that looks almost right but is not. What AI-powered generation changes is the speed of getting from 'we should test this' to 'we have a working test', and in agentic approaches, the resilience of that test when small things about the page change, such as a button moving or being renamed.

Self-Healing and Locator Strategy

A key technical idea behind many AI-powered approaches is finding an element by more than one signal. Rather than relying on a single brittle CSS selector, a well-built system tries several ways of identifying the right element, for example a test id, an accessible role and name, visible text, or a label, falling back from one to the next. This is what allows a generated test to keep working even after some cosmetic changes to the page, and it is also the basis for 'self-healing': when an element can no longer be found, a system with this capability can look at the current page and work out a replacement step, rather than simply failing.

Hosted products are starting to combine this idea with full AI agents. For example, xtest lets you describe a test in plain English in its Test Lab, pick a device, and watch a test agent, powered by Claude, carry the test out live; when a saved step stops matching the app later, xtest has the test agent repair just that step rather than the whole test. This course will not teach you any single vendor's interface, but understanding this pattern will help you evaluate any tool, including xtest, that claims to do AI-powered test generation.

From Manual Scripts to AI-Generated Tests

For most of the history of test automation, writing a test meant writing code: opening a browser automation library, finding elements with selectors, and chaining together actions and assertions by hand. This gave testers full control, but it also meant that every UI change could break multiple tests, and that writing a comprehensive suite took significant engineering time.

The first wave of improvement came from record-and-playback tools, which captured a human's clicks and typing into a script automatically. These reduced the time to create a first version of a test, but the resulting scripts were often brittle, tied closely to exact selectors and timing, and hard to read or maintain by hand afterward.

AI-powered generation is a further step: instead of only capturing what a human did, a model can be asked to describe, in a structured way, what a human intends, and can fill in the implementation details itself. This includes choosing robust locators, adding reasonable waits, and in some systems, deciding the next action live based on what is actually on the screen at that moment, rather than following a fixed script that assumes the page never changes. Understanding this progression helps explain both the appeal of AI-generated tests and why they still need human oversight: a model that decides on its own course of action can also decide incorrectly, which is why review and verification remain essential steps, not optional extras.

How AI Test Generation Works Under the Hood

At a technical level, most AI-powered test generation systems work from the same raw materials: the structure of the page (its HTML, its accessible roles and names), a visual representation such as a screenshot, and a plain-language description of the goal. A language model is given some combination of these and asked to produce either a finished script in a known framework, or a single next action when working step by step as an agent.

When generating a static script, the model typically produces familiar automation code: find an element, perform an action, assert a result, in a syntax any engineer can read and version-control like any other code. When acting as a live agent instead, the model is given a fixed set of possible actions (click, type, scroll, switch tabs, and so on) and chooses one at a time, observing the result before deciding the next step, which is what gives this approach its resilience to small UI changes.

Both approaches typically include some strategy for locating elements that does not depend on a single brittle selector, since that is the main reason traditional scripts break. A locator that falls back through several signals, such as a test id, then a role and accessible name, then visible text, survives far more UI changes than a hard-coded CSS path. Knowing this helps you judge any AI test generation tool you are evaluating: ask what signals it uses to find elements, and what happens when none of them match anymore.

# Launch Playwright's built-in code generator against a real site
# It records your clicks and typing and writes a Playwright test for you
npx playwright codegen https://example.com

Playwright's codegen tool is a real, publicly available way to turn a recorded interaction into a runnable test script, illustrating the 'record-and-generate' pattern discussed in this section.

// A Playwright test using a resilient locator strategy:
// prefer role and accessible name over a brittle CSS selector
const { test, expect } = require('@playwright/test');

test('search returns matching results', async ({ page }) => {
  await page.goto('https://example.com');
  await page.getByRole('searchbox', { name: 'Search' }).fill('running shoes');
  await page.getByRole('button', { name: 'Search' }).click();
  await expect(page.getByRole('heading', { name: /results/i })).toBeVisible();
});

An example of the kind of script a generation tool should aim to produce: it finds elements by role and accessible name rather than a fragile selector, making it more likely to survive small UI changes, the same principle behind self-healing approaches.

Tips

  • Always read a generated test before trusting it; a model can produce a script that runs successfully but checks the wrong thing, such as asserting that a page loaded rather than that the right data appeared on it.
  • Prefer locator strategies based on role, accessible name, label or test id over raw CSS selectors, whether you are writing a test by hand or reviewing one a model generated, since these survive far more UI changes.
  • Start AI-assisted generation on your most stable, well-defined flows (login, checkout, search) before trying it on pages that change frequently, so you can judge the tool's quality without fighting constant UI churn at the same time.

Common pitfalls

  • Trusting a generated test without running it against a failing case: a test that always passes, even when the feature is broken, is worse than no test at all. Always confirm a new test fails when you introduce a real bug before relying on it.
  • Letting a model choose brittle, single-attribute selectors because that is what it happened to see in the page's raw HTML. Review and, where needed, rewrite locators to use stable attributes like test ids or accessible roles rather than auto-generated class names.

Writing Effective Instructions for AI Test Generation

An AI system that turns plain language into a test, whether it writes a static script once or acts as a live agent on a running app, can only be as good as the instructions it receives. Vague instructions produce vague tests: steps get skipped, assumptions get made silently, and the wrong element gets clicked. This section teaches you to write instructions that read like a short, unambiguous recipe rather than a casual description of what you'd like to happen.

The core skill is turning a loose idea ("check that login works") into a sequence of concrete actions and checkpoints ("open the login page, enter a valid email and password, click Sign in, and confirm the dashboard heading is visible"). Good instructions separate setup, actions, and expected outcomes so the model or agent never has to guess which part of your sentence is a step and which is a success condition.

Equally important is context calibration. Too little context forces the AI to infer things it cannot know, like which of three similar buttons is the right one. Too much context, such as pasting an entire style guide or unrelated business rules, dilutes the instruction and increases the chance the model focuses on the wrong detail. The goal is the minimum context that removes ambiguity.

Finally, real user journeys are rarely a single straight line. They branch ("if the user already has items in their cart..."), they depend on prior state, and they sometimes require a judgment call ("an acceptable error message"). Writing for these cases means being explicit about branches and tolerances, and knowing when to split one journey into several smaller, independently testable scenarios instead of one long, fragile one. In a tool like xtest's Test Lab, you describe a test in plain English, pick a device, and a test agent carries it out on that device while you watch it live, so the clarity of that first description directly determines how reliable the resulting run and its saved steps will be.

Structuring Scenarios into Steps and Expected Outcomes

The most reliable instructions read as a numbered or bulleted sequence rather than a paragraph of prose. Each line should contain one action, and each action that matters should be paired with a verifiable outcome: not just "submit the form" but "submit the form and confirm a success banner appears." This structure does three things. First, it removes sequencing ambiguity, since the AI does not have to infer the order of operations from loose grammar. Second, it gives the system a checkpoint after each meaningful action, which matters because a scenario that only checks the very last screen can pass even when an earlier step silently did the wrong thing. Third, it makes the scenario easier to debug afterward, because a failure can be traced to a specific numbered step rather than to "somewhere in the flow."

A useful habit is to write the expected outcome before the action that produces it, as a kind of acceptance criterion, then fill in the action. For example: "Expected: the cart shows 2 items. Action: add the same product twice from the product page." This ordering forces you to be precise about what success actually looks like, rather than assuming it is obvious. It also exposes steps that have no observable outcome at all, which is usually a sign the step is either unnecessary or needs a checkpoint added. Scenarios written this way transfer cleanly whether they are consumed by a script generator or carried out live by an agent watching the same screen you are.

Giving Context Without Overwhelming the Model

Context should answer the questions an AI cannot answer by looking at the screen alone: which account to use, what state the app should start in, what counts as valid test data, and what should be ignored. A login scenario benefits from a sentence like "use the test account test@example.com with password Testing123," because no amount of visual inspection reveals the right credentials. By contrast, restating the layout of a page the AI will see directly, such as describing every button on the screen, adds nothing and increases the chance that a stale description conflicts with what is actually rendered.

A good rule of thumb is to include exactly the facts that are true regardless of what the page currently looks like: account details, business rules, data constraints, and the definition of success. Leave out anything that is purely visual or that changes often, since the AI reading the live page will discover that for itself. When a scenario depends on prior state, such as a cart that must already contain an item, say so explicitly rather than assuming the AI will intuit it, and prefer scenarios that set up their own state in an early step over ones that silently depend on whatever was left over from a previous run. This keeps each scenario self-contained and repeatable, which matters most once a passing run is expected to be replayed later with the same steps rather than reasoned through from scratch each time.

Weak instruction:
"Test that checkout works."

Strong instruction:
1. Go to the product page for "Wireless Mouse".
2. Add it to the cart.
3. Expected: cart icon shows a count of 1.
4. Go to checkout.
5. Enter shipping address: 123 Main St, Springfield, 90210.
6. Use test card 4242 4242 4242 4242, any future expiry, any CVC.
7. Click "Place order".
8. Expected: a confirmation page appears with an order number starting with "ORD-".

The weak instruction leaves every detail, including what success looks like, to guesswork. The strong version separates setup, actions and expected outcomes line by line, giving a model or live agent an unambiguous path to follow and a concrete way to decide pass or fail at each stage.

// Example of the kind of Playwright test a clear, step-based
// instruction like the one above should translate into cleanly.
import { test, expect } from '@playwright/test';

test('checkout with a single item', async ({ page }) => {
  await page.goto('https://shop.example.com/products/wireless-mouse');
  await page.getByRole('button', { name: 'Add to cart' }).click();
  await expect(page.getByTestId('cart-count')).toHaveText('1');

  await page.getByRole('link', { name: 'Checkout' }).click();
  await page.getByLabel('Street address').fill('123 Main St');
  await page.getByLabel('City').fill('Springfield');
  await page.getByLabel('ZIP code').fill('90210');
  await page.getByLabel('Card number').fill('4242 4242 4242 4242');

  await page.getByRole('button', { name: 'Place order' }).click();
  await expect(page.getByText(/ORD-\d+/)).toBeVisible();
});

This script mirrors the strong instruction step for step, each action followed by a check. Writing instructions with this level of precision makes it far easier to verify, by hand or by eye, that a generated script actually does what the scenario intended.

Tips

  • Write one action per line and attach an expected outcome to every action that matters, not just the final one.
  • State facts the AI cannot see, like test accounts, starting state and data constraints, but skip describing the visible layout.
  • When a journey branches, spell out the condition explicitly ("if the cart is empty, expect a message instead of a total") rather than leaving the branch implied.
  • Prefer several short, self-contained scenarios over one long journey that depends on invisible prior state.

Common pitfalls

  • Describing only the end goal ("test that search works") without intermediate checkpoints, which lets an earlier mistake slip through unnoticed as long as the final screen happens to look right.
  • Overloading the instruction with irrelevant detail, such as full page descriptions or unrelated business context, which can distract the model from the actual steps and expected outcomes.

Validating and Maintaining AI-Generated Tests

Before an AI-generated test earns a permanent place in your suite, it should pass a short but deliberate review. Treat the AI's first draft the way you would treat a pull request from a new teammate: read every assertion, every locator and every wait condition before you let it run unattended in CI. A test that merely 'passes' today is not the same as a test that checks the thing you actually care about, and the gap between those two is where AI-generated suites quietly rot.

This section covers three checkpoints: confirming the assertions map to the real requirement, confirming the locators the AI chose will still find the right element next month, and setting up a repeatable process for approving changes when generated steps get repaired after a UI change. Skipping any one of these turns a time-saving tool into a liability, because a confidently wrong test is worse than no test: it gives you false confidence while a real regression ships.

The review does not need to be heavyweight. A five-minute read of the generated script, a quick run against a staging build, and a one-line note on why each assertion matters is usually enough for a simple flow. For anything touching money, data deletion or account state, slow down and read every line, because these are exactly the actions a careless locator or an over-broad assertion can get wrong in a way that only shows up in production.

Finally, treat test maintenance as an ongoing discipline, not a one-time gate. UI changes, new environments and flaky network conditions will all eventually force a generated test to adapt, and you want a process in place before that happens, not after a broken test has been silently skipped for three weeks.

Matching Assertions to the Real Requirement

An AI test generator is good at producing a script that runs, but it has no way of knowing which parts of the screen actually matter to your business unless you tell it. The most common failure mode is an assertion that checks something trivially true, like a page title or a static label, while leaving the behaviour you actually care about unverified. Before accepting a generated test, write out the requirement in one sentence ('a user who submits a valid order sees a confirmation number and an updated order count') and check that every clause has a matching assertion. If the generated script only checks that a confirmation message appeared, and not that the order count updated, it has partial coverage dressed up as full coverage.

It also helps to look for the inverse: assertions that are too strict. A generated test that checks an exact timestamp or a full error message string will break the moment copy changes, even though the underlying behaviour is still correct. Prefer assertions that check the meaning of the output (an order was created, an error was shown) over assertions that check its exact wording.

A practical habit is to keep a short requirements note next to each test, even one line, so a future reviewer (human or AI) can check the test still matches intent after a repair. Without that anchor, a test can drift away from the requirement one small fix at a time until nobody remembers what it was originally meant to prove.

Locator Stability: Reading the Script Like a Reviewer

Locators are the part of a generated test most likely to look fine today and fail in three weeks. An AI generator working from a live page will often grab whatever uniquely identifies an element right now, which can mean a CSS path built from div nesting, an auto-generated class name, or a visible text string that marketing will rewrite next sprint. None of these are wrong exactly, but they rank differently on durability, and a reviewer should know the order of preference: a dedicated test id first, then a stable id, then accessible role and name, then a label or placeholder, then visible text, with a CSS path as the last resort.

When you review a generated script, look specifically for CSS selectors with index positions (like nth-child(3)) or selectors tied to classes that look auto-generated (hashes, utility-class soup). These are the first things to break after a styling change, even when the user-facing behaviour hasn't changed at all. Where possible, push back a layer: ask the team to add a test id to the element, then regenerate or hand-edit the locator to use it.

It is worth running a new test twice in a row and once more after a small, deliberate UI tweak (reordering a list, renaming a CSS class) before trusting it in a schedule. A locator that survives a cosmetic change you made on purpose is far more likely to survive the real ones that happen by accident.

Approving Repairs Without Losing Control

No generated test survives contact with a changing UI forever. The useful question is not whether a saved test will eventually need repair, but how you find out when it does and who signs off on the fix. A sensible process has three parts: a repair is logged with a diff of what changed, a person reviews whether the fix still checks the same behaviour, and only a repair that changes what the test actually verifies needs a human in the loop before it ships. In xtest, this is built in directly: when a saved step stops working, the test agent repairs only that step, and a repair that would change what the test checks waits for a person to approve it before it is used again.

The same principle applies even without that kind of built-in gate: a locator swap because an id changed is low risk and can often be auto-approved, but a repair that drops an assertion, widens a wait, or changes which element gets clicked is exactly the kind of change that deserves a second pair of eyes. Build your approval process around that distinction rather than treating every repair the same way.

Keep a short changelog per test (even a commit message is enough) so that six months from now, when the test fails again, whoever investigates can see what was repaired last time and whether the same root cause is recurring.

import { test, expect } from '@playwright/test';

test('checkout updates order count after submit', async ({ page }) => {
  await page.goto('https://shop.example.com/cart');

  // Prefer a dedicated test id over a CSS path or visible text
  await page.getByTestId('submit-order').click();

  // Assert the behaviour that matters, not just that *something* changed
  await expect(page.getByTestId('order-confirmation')).toBeVisible();
  await expect(page.getByTestId('order-count')).toHaveText('1');
});

A reviewed version of a generated checkout test: it swaps a brittle CSS selector for a test id, and checks both the confirmation message and the order count, since the requirement was that both update together.

// Before review: fragile locator, weak assertion
await page.locator('div.ck8f2 > span:nth-child(3)').click();
await expect(page.locator('text=Thank you')).toBeVisible();

// After review: stable locator, assertion tied to the requirement
await page.getByRole('button', { name: 'Confirm order' }).click();
await expect(page.getByTestId('order-id')).not.toBeEmpty();

Side-by-side comparison showing the kind of edit a reviewer should make: replacing a positional CSS selector with an accessible role query, and replacing a loose text check with an assertion on the actual data the requirement cares about.

Tips

  • Write the requirement as a single sentence before reading the generated script, then check every clause of that sentence has a matching assertion.
  • Rank locators by durability (test id, id, role and name, label, placeholder, visible text, CSS path) and push back on anything lower than label when a test id could be added instead.
  • Run a new test twice, and once more after a small deliberate UI tweak, before trusting it in a schedule; a locator that survives an intentional change is a good sign.

Common pitfalls

  • Accepting a test because it 'passes' without checking what it actually asserts: a confirmation message appearing is not the same as an order count updating, and an AI generator will happily check only the easier of the two unless told otherwise.
  • Treating every repaired step the same way: auto-approving a locator swap is usually fine, but a repair that drops or loosens an assertion changes what the test proves and needs a human to review it before it ships again.

Integrating AI-Generated Tests into CI/CD

Once an AI test agent has worked out a flow and saved it as a passing test, that test should earn its place in the pipeline rather than sit only in a dashboard. Integrating AI-generated suites into CI/CD means deciding where in the pipeline they run, what happens when one fails, and how the team hears about it fast enough to act.

The first decision is placement: does a suite run on every pull request, on merge to main, on a nightly schedule, or only before a release tag? Fast, stable suites (smoke-level flows through login, checkout, core navigation) belong on pull requests because a long wait discourages developers from running tests at all. Slower or less stable suites (full regression across many pages, exploratory-style passes) are better as scheduled or nightly jobs so they do not block everyday work.

The second decision is severity: a failing test should either break the build or simply inform. Treat these differently in your pipeline configuration rather than bundling every suite into one pass/fail gate.

The third piece is the feedback loop. A failure discovered at 2am is only useful if a human sees it before the next deploy, and a repair the AI made to a broken step is only safe if someone reviews what changed before it is trusted again. xtest's docs for CI/CD, at https://xtest.io/docs/integrations/ci-cd, give a ready script using curl and jq that starts a suite from GitHub Actions, GitLab CI, Jenkins or CircleCI and fails the build unless every test passed, which is a useful pattern to copy even if you build your own runner against a different tool.

Blocking Gates vs Informational Runs

Not every AI-generated test should have the power to stop a deploy. A practical split is to classify suites by two questions: how stable is this flow (does it rarely produce false failures), and how costly is a missed regression here (is this a payment flow or a settings page nobody uses)?

Flows that are both stable and high-value (login, checkout, core search) should block the build: if they fail, the pipeline exits non-zero and the deploy stops. Flows that are newly generated, still being tuned, or lower-stakes (a cosmetic page, an admin-only report) should run informationally: the job still executes and reports results, but a failure only posts a notification or opens a ticket rather than failing the build.

In practice this means running two (or more) separate jobs or steps in your pipeline configuration, each pointed at a different suite, with different exit-code handling. A common mistake is putting a brand-new AI-generated suite straight into the blocking gate before it has proven itself stable over a few days of real runs; let it run informationally first, watch it for a week, then promote it.

It also helps to keep the blocking suite small and fast. A pipeline step that takes twenty minutes will get skipped, disabled, or run only on a schedule by frustrated engineers, which defeats the purpose of having a gate at all. Reserve the large, slow suites for nightly or pre-release jobs where time pressure is lower.

Triggering Runs and Reading Results

A CI job needs three things from any test runner: a way to start a run, a way to poll or wait for it to finish, and a way to read back a pass/fail result plus details on what failed. Design your pipeline step as a small wrapper: call the start endpoint or command, loop with a short sleep while the run is in progress, then fetch and print the result, exiting with a matching status code.

Keep the credentials for this call in your CI provider's encrypted secrets store, never checked into the repository or printed in logs. Rotate any such key immediately if a log ever shows it by accident.

Watch your limits too. If a tool caps how many tests a single run can include, a growing suite may need to be split into several runs that your pipeline kicks off in sequence or parallel, with the build only passing when all of them do. Likewise, if a given account is permitted only a handful of concurrent automated runs, a burst of pull requests opened at once can hit that ceiling; queue excess jobs rather than letting them fail outright, and make that queuing visible in your CI logs so a developer does not mistake a queued run for a stuck one.

Finally, treat the result payload as structured data, not just a pass/fail flag: capture which specific test failed and why, so the next section's feedback loop has something concrete to report rather than a bare red X.

Closing the Feedback Loop

A test that fails silently in a log nobody reads provides no value. Once a run finishes, push its outcome somewhere a human will actually see it: a chat notification, a ticket created automatically from a failure, or a build-status badge on the pull request itself.

For AI-generated and self-healing tests specifically, add one more loop: repairs. When a saved test's step stops matching the current page and gets automatically repaired, that repair should be visible and, if it changes what the test actually checks, reviewed by a person before it is trusted in a blocking gate. Route repair notifications to the same channel as failures so nothing gets missed, and set a routine, say a short weekly check, where someone reviews pending repairs rather than letting them pile up.

A second useful loop is trend tracking: a single failure might be flaky, but a test that fails on three consecutive runs is a real regression. Rather than paging someone on every red run, consider a rule like opening an urgent alert only after a test fails twice in a row, while a single failure just gets logged.

Last, keep the loop short. The point of running tests in CI at all is to catch problems while the context (the commit, the author, the diff) is still fresh. A feedback mechanism that reports failures a day later, after three more commits have landed, has lost most of its value; aim for notifications within minutes of the run finishing.

name: e2e-tests
on:
  pull_request:
    branches: [main]

jobs:
  smoke-blocking:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npx playwright install --with-deps
      - name: Run smoke suite (blocking)
        run: npx playwright test tests/smoke --reporter=line

  regression-informational:
    runs-on: ubuntu-latest
    continue-on-error: true
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npx playwright install --with-deps
      - name: Run full regression suite (informational)
        run: npx playwright test tests/regression --reporter=line

A GitHub Actions workflow with two jobs: a fast smoke suite that blocks the pull request if it fails, and a larger regression suite marked continue-on-error so it reports results without stopping the build.

#!/usr/bin/env bash
set -euo pipefail

RUN_ID=$(curl -s -X POST "$TEST_API_URL/runs" \
  -H "Authorization: Bearer $TEST_API_KEY" \
  -d '{"suite": "checkout-smoke"}' | jq -r '.id')

echo "Started run $RUN_ID, polling for completion..."

STATUS="running"
while [ "$STATUS" = "running" ]; do
  sleep 10
  STATUS=$(curl -s "$TEST_API_URL/runs/$RUN_ID" \
    -H "Authorization: Bearer $TEST_API_KEY" | jq -r '.status')
done

if [ "$STATUS" != "passed" ]; then
  echo "Run $RUN_ID finished with status: $STATUS"
  curl -s "$TEST_API_URL/runs/$RUN_ID" -H "Authorization: Bearer $TEST_API_KEY" | jq '.failures'
  exit 1
fi

echo "Run $RUN_ID passed."

A generic shell script, using curl and jq, that starts a test run against a REST-style test API, polls until it finishes, prints any failures, and exits non-zero to fail the build if the run did not pass. Substitute your own test runner's API URL and key.

Tips

  • Start new AI-generated suites as informational-only jobs and promote them to blocking gates only after they have proven stable over several days of real runs.
  • Keep blocking suites short and focused so pipeline wait times stay low enough that nobody is tempted to skip or disable them.
  • Store any API keys or tokens used to trigger test runs in your CI provider's secret store, and rotate them if they ever appear in a log.

Common pitfalls

  • Putting every generated test into one all-or-nothing gate: a single flaky or low-value test then blocks unrelated deploys. Split suites by stability and business value instead.
  • Letting repair notifications and failure alerts pile up unread in a channel nobody checks: route them somewhere actively monitored and review pending repairs on a regular cadence.

Exercises

Exercise 1: Generate and Harden Your First AI-Assisted Test

In this exercise you will use Playwright's code generation tool to capture a real user flow on a public demo site, then apply the locator strategy principles from this section to make the generated test more resilient. You will finish by deliberately breaking the flow's expected behavior to confirm your test actually catches the problem, which is the single most important habit to build when working with any AI-generated or tool-generated test. This exercise should take about 30 minutes and assumes you have Node.js installed along with the Playwright test runner.

  1. Install Playwright in a new project folder and run 'npx playwright codegen' against a public demo site such as a sample shopping or to-do app.
  2. Perform a simple multi-step flow in the opened browser window, for example searching for an item or adding a task, and let the tool record the actions.
  3. Stop the recorder and copy the generated script into a test file.
  4. Review each locator in the generated script; replace any brittle, auto-generated CSS selector with a role-based or test-id based locator where possible.
  5. Run the test once to confirm it passes against the real site.
  6. Temporarily change your assertion to expect an incorrect outcome (for example, expect text that should not appear) and re-run the test to confirm it now fails, proving the assertion is actually checking something meaningful.
  7. Revert the assertion to the correct expected outcome and run the test one final time to confirm it passes.

Expected outcome: A working Playwright test file that passes against the real flow, uses resilient locators (role, label, or test id based rather than fragile CSS paths), and that you have personally verified fails when the expected outcome is wrong, demonstrating that the test provides real coverage rather than a false sense of security.

Exercise 2: Write a Natural-Language Test Specification

In this exercise you will practice the skill of describing a test scenario clearly enough that it could be handed to an AI test generation tool and produce a correct result, without ambiguity about what counts as success. You will write specifications for three different scenarios of increasing complexity, then exchange them with a partner (or review them yourself after a break) to check whether every step and expected outcome is unambiguous. This exercise focuses on the instruction-writing skill itself rather than any specific tool, since that skill transfers across every AI-powered testing product you might use.

  1. Pick a public website you are familiar with (a demo e-commerce site, a note-taking app, or similar).
  2. Write a plain-language specification for a simple one-step scenario, such as 'the search box returns results for a known term', including a precise expected outcome.
  3. Write a specification for a medium scenario involving at least three steps, such as adding an item, editing it, and confirming the edit persisted.
  4. Write a specification for a scenario that includes a negative case, such as submitting a form with missing required information and expecting a specific error message.
  5. Review each specification and mark any sentence where two different people could reasonably disagree about what should happen; rewrite those sentences to remove the ambiguity.
  6. If working with a partner, swap specifications and attempt to execute each other's scenario manually, step by step, exactly as written, noting any point where the instructions were unclear.

Expected outcome: Three clearly written test specifications, each with unambiguous steps and a precise expected outcome, that another person (or an AI system) could follow without needing to guess your intent, along with notes on any ambiguity you found and corrected.

Quiz

1. What is the main advantage of an agentic AI approach to test execution, where the model decides the next action live, compared to a fully pre-written script?

  1. It requires no review of the resulting test at any point
  2. It can adapt to small changes in the page at run time by observing the current state before acting
  3. It eliminates the need for any locator strategy
  4. It guarantees the test will always pass
Show answer

B. It can adapt to small changes in the page at run time by observing the current state before acting

An agentic approach observes the actual state of the page before deciding its next action, which allows it to cope with small UI changes that would break a fixed, pre-written script. It does not remove the need for review, does not eliminate locator strategy (it still needs a way to find elements), and certainly does not guarantee a test will pass, since a real bug should still cause it to fail.

2. Why is locating elements by role, accessible name, label or test id generally preferred over a raw CSS selector in a generated test?

  1. CSS selectors are slower to execute than other locator types
  2. These signals are more stable across UI changes, making the test less likely to break from cosmetic edits
  3. CSS selectors cannot be used in any modern testing framework
  4. Role-based locators automatically generate test data
Show answer

B. These signals are more stable across UI changes, making the test less likely to break from cosmetic edits

Attributes like role, accessible name, label and test id tend to stay the same even when a page's visual styling or layout changes, whereas CSS selectors (especially auto-generated class names) often break with minor cosmetic edits. This has nothing to do with execution speed or data generation.

3. A newly generated test passes on its first run. What is the most important next step before trusting it as part of your suite?

  1. Immediately schedule it to run nightly without further review
  2. Delete the test and write it by hand instead
  3. Verify it actually fails when the expected behavior is broken, confirming its assertions check something meaningful
  4. Share it with the whole team as a finished deliverable
Show answer

C. Verify it actually fails when the expected behavior is broken, confirming its assertions check something meaningful

A test that passes does not prove it is checking the right thing; it could pass even if the feature is broken. Deliberately breaking the expected behavior and confirming the test then fails is the standard way to validate that a test provides real coverage, for both hand-written and AI-generated tests.

4. Which AI model powers the test agents in xtest, a hosted platform for end-to-end testing with AI test agents?

  1. GPT-4, made by OpenAI
  2. Gemini, made by Google
  3. Claude, made by Anthropic
  4. Llama, made by Meta
Show answer

C. Claude, made by Anthropic

xtest's test agents are powered by Claude, made by Anthropic. In xtest you describe a test in plain English in its Test Lab, pick a device, and watch the test agent carry it out live.

5. Why should an ambiguous test specification be rewritten before it is handed to an AI test generation tool?

  1. Ambiguous specifications make scripts run faster
  2. An AI system, like a human, will resolve ambiguity with its own assumption, which may not match what you actually intended to test
  3. Ambiguity is required for the AI to generate any code at all
  4. Test specifications are never read by AI tools, only by humans
Show answer

B. An AI system, like a human, will resolve ambiguity with its own assumption, which may not match what you actually intended to test

Just like a human reading vague instructions, an AI system faced with an ambiguous specification will fill the gap with some assumption, which may not reflect what you actually wanted verified. Writing clear, unambiguous steps and expected outcomes reduces the chance of a generated test checking the wrong thing.

Related docs

All courses