> 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/testing-with-ai-coding-agents/claude-code-testing.md).

# Testing with Claude Code

Use Claude Code for contract-driven unit, integration and Playwright tests, then create and verify browser acceptance tests with ContextQA MCP.

## Quick answer

Claude Code can help design tests, edit test files and run the test tools already installed in your repository. Start with an independently defined expected result, generate the smallest useful test, and inspect the actual runner output. Add ContextQA MCP when you want to create and execute managed browser tests against a reachable application. ContextQA MCP does not replace your Jest, Vitest or pytest runner.

This walkthrough uses an illustrative invoice-discount change: a discount is allowed through its expiry time, cannot make the total negative, and must appear correctly in the saved invoice. Adapt the contract and paths to your application; the examples are instructions, not recorded test results.

## Before you start

Have Claude Code working in the correct repository, its dependencies installed, the feature's acceptance criteria, and a disposable test environment. Identify the branch, application version and test-data reset procedure. Use test accounts and approved secret storage; do not paste production credentials into prompts.

Choose the lowest test level that can prove each behavior:

| Question                                                    | Appropriate test                                                          |
| ----------------------------------------------------------- | ------------------------------------------------------------------------- |
| Does the discount calculation handle boundaries?            | [Unit test](/testing-with-ai-coding-agents/unit-testing.md)               |
| Does invoice creation persist the correct total?            | [Integration test](/testing-with-ai-coding-agents/integration-testing.md) |
| Can a user apply and remove a valid discount?               | [Functional test](/testing-with-ai-coding-agents/functional-testing.md)   |
| Does creating, saving and reopening an invoice preserve it? | [End-to-end test](/testing-with-ai-coding-agents/end-to-end-testing.md)   |

## 1. Establish the commands and current baseline

Start Claude Code in your repository:

```bash
cd /path/to/your/repository
claude
```

Claude Code supports inspecting existing tests and following repository conventions. See its [official testing workflow](https://code.claude.com/docs/en/common-workflows#work-with-tests).

Give it a bounded discovery task before requesting edits:

```
Read this repository's instructions, package/build configuration and the
existing invoice tests. Identify the test runner, exact focused test command,
fixture setup and cleanup. Run the existing focused suite and record its
result. Do not install a second framework or change application code.
Separate pre-existing failures from the tests we add next.
```

Keep the baseline output. A missing database or unavailable browser is an environment blocker; it is not evidence that the feature passes or fails.

## 2. Turn the requirement into independent examples

Agree the currency rounding and expiry rules before asking the agent to write assertions. If the requirement is silent, label the assumption for review rather than letting the current implementation become the specification.

```
Our accepted contract is: totals use integer minor units; a discount cannot
reduce an invoice below zero; expiry is inclusive at the stated UTC timestamp.
Create a decision table for a normal discount, an excessive discount, expiry
one second before/at/after the boundary, and an invalid discount identifier.
Calculate expected totals from this contract, not by calling the production
calculator. Identify any remaining ambiguity before writing test files.
```

A valuable assertion checks the amount owed. Checking only that the calculator was called, or that an object exists, does not prove pricing behavior. Control the test clock so tomorrow's date does not change the verdict.

## 3. Write unit and integration tests in small increments

Ask Claude to add the approved cases using the existing runner. Unit tests should isolate the calculation; integration tests should exercise the persistence boundary with a disposable database or the repository's existing test service.

```
Implement the approved decision table in the existing test files. Use fixed
time and deterministic input data. Keep unit tests independent of network
services. For the integration test, save and reload an invoice and assert the
stored total and discount identifier. Clean up only this test's records.
Run the focused commands. Show assertions and results before proposing a fix.
Do not weaken expectations, update snapshots blindly, or skip failing cases.
```

For a confirmed defect, the new regression test should expose that defect before a repair and pass after it. For new behavior, an initial failure may instead mean the feature is not implemented yet. Keep the distinction in the review.

## 4. Add one browser journey where it adds evidence

Use the repository's browser framework. If it uses Playwright, follow the [Playwright testing guide](/testing-with-ai-coding-agents/playwright-testing.md) for fixtures, locators and traces.

```
Add one browser test for our disposable invoice account. Open a new invoice,
apply the approved discount, assert the exact visible total, save, then reopen
the invoice and assert persistence. In a separate test with a fresh invoice,
test an expired discount and verify the original total remains unchanged.
Reuse existing fixtures and user-facing locators.
Run against the specified test URL. Report the runner command, exit status,
test counts and failure artifacts. Do not treat a screenshot alone as a pass.
```

Check which services were real and which were mocked. An intercepted save response verifies UI behavior; it does not prove that the backend stored the invoice.

## 5. Connect Claude Code to ContextQA MCP

For managed browser execution, add the hosted server:

```bash
claude mcp add --transport http contextqa https://mcp.contextqa.com/mcp
claude mcp list
```

In an interactive Claude Code session, open `/mcp`, select ContextQA and complete OAuth sign-in. Wait for the browser callback to finish. The command and authentication flow follow [Claude Code's MCP documentation](https://code.claude.com/docs/en/mcp) and the [ContextQA server setup](https://mcp.contextqa.com/docs). The account must have access to the intended ContextQA workspace.

The MCP connection gives Claude tools for ContextQA. It does not make your laptop's files or `localhost` application reachable by a remote test runner. Use a reachable test deployment or an organization-approved network setup for your application. Confirm the actual target environment before execution.

## 6. Discover, create, review, execute and inspect

First make a read-only request:

```
Using ContextQA, inspect the connected tool names and schemas. List available
test environments and search for existing invoice-discount tests. Show matching
test IDs and steps. Do not create, update or execute anything yet.
```

Then supply the approved target URL and criteria:

```
Prepare the missing browser cases in our designated test workspace for the
invoice-discount scenario above. Use [approved test URL] and the configured
test account. Keep the valid-discount and expired-discount cases separate,
each with a fresh invoice and explicit starting total.
Reuse matching cases where they exist. Return case IDs and complete steps
for review. Do not execute it until the steps and environment are confirmed.
```

After review, ask Claude to execute that specific case. The documented flow is `execute_test_case`, `get_execution_status`, then `get_test_case_results` and `get_execution_step_details`, using the IDs returned by the tools. Follow the connected schema and [execution reference](/mcp-server/tool-reference/execution-and-results.md); do not guess IDs or reuse an older result.

Record the case ID, execution/result ID, target build, verdict, failed assertion and evidence links. A completed execution still needs a pass/fail result. A correctly rejected expired discount is a **passing negative test**, not a test failure.

## Export the reviewed test

Ask for supported export options for that case, then choose the required framework. Inspect the returned artifact location before assuming a hosted export wrote to your laptop. Follow [export and portability](/testing-with-ai-coding-agents/export-and-portability.md), review generated code, and run it in your own CI before accepting equivalence. Export is a starting point for repository ownership, not proof that every fixture or assertion transfers unchanged.

## Troubleshooting and FAQ

**Claude wrote tests but did not run them.** Request the exact command and output. If execution is blocked, report the blocker and leave the result unverified.

**The tests pass only after retries.** Preserve the first failure, compare timing and fixture state, and investigate before increasing retries.

**MCP is connected but finds no tests.** Confirm the account, workspace and search scope. An empty search is not a connection failure. Use [connection troubleshooting](/mcp-server/troubleshooting.md).

**Can ContextQA run my local unit suite?** Run that suite through Claude Code's repository tools. Use ContextQA for the application tests exposed by its connected tools.

## Try the workflow

[Connect ContextQA MCP and run your first reviewed test](/mcp-server/installation-and-setup.md). To evaluate shared suites, evidence retention or team workflows, [book a ContextQA demo](https://contextqa.com/book-a-demo/?utm_source=learning.contextqa.com\&utm_medium=referral\&utm_campaign=docs_demand_gen\&utm_content=claude-code-testing) with one representative application journey.


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://learning.contextqa.com/testing-with-ai-coding-agents/claude-code-testing.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
