Skip to content

Testing with Claude Code

Learn how to write, run, and debug tests with Claude Code.

What You'll Learn

  • Writing unit tests
  • Running test suites
  • Debugging failing tests
  • Test coverage strategies

Running Tests

Basic Test Run

> Run the tests

Claude identifies your test framework and runs tests: - npm test - pytest - go test - cargo test - etc.

Specific Tests

> Run only the auth tests

> Run the test for getUserById function

> Run tests matching "login"

With Options

> Run tests with verbose output

> Run tests and show coverage

> Run tests in watch mode

Understanding Test Output

When Tests Pass

> Run the tests

✓ All 42 tests passed in 3.2s

When Tests Fail

> Run the tests

  FAIL src/auth.test.js
    ✕ should validate email format (12ms)

    Expected: true
    Received: false

    at validateEmail (src/utils.js:15:10)

Claude can then help:

> Why is the email validation test failing?

Writing Tests

For Existing Code

> Write tests for the UserService class

Claude: 1. Reads the class 2. Identifies testable functions 3. Generates appropriate test cases

With Specifications

> Write tests for validatePassword that check:
  - Minimum 8 characters
  - At least one uppercase
  - At least one number
  - Common passwords rejected

Following Existing Patterns

> Write tests for ProductService following the same
  pattern as UserService.test.js

Test Types

Unit Tests

> Write unit tests for the calculateDiscount function

Tests isolated logic with mocked dependencies.

Integration Tests

> Write an integration test for the checkout flow

Tests multiple components working together.

End-to-End Tests

> Write an E2E test for user registration

Tests the full user journey.

Test-Driven Development

Claude supports TDD workflows:

Step 1: Write the Test First

> Write a test for a function called `slugify` that:
  - Converts "Hello World" to "hello-world"
  - Removes special characters
  - Handles empty strings

Step 2: Implement the Function

> Now implement slugify to pass those tests

Step 3: Run and Verify

> Run the slugify tests

Debugging Failing Tests

Understand the Failure

> This test is failing:

  expect(result).toEqual({ name: 'John', age: 30 });

  Received: { name: 'John', age: '30' }

  What's wrong?

Claude identifies the type mismatch.

Trace the Issue

> The test passes locally but fails in CI. Help me understand why.

Fix the Test vs Fix the Code

> Is the test wrong or is the code wrong?

Claude analyzes the expected behavior.

Coverage

Check Coverage

> What's the test coverage for the auth module?

Improve Coverage

> Which functions in utils.js are not tested?

> Add tests to cover the edge cases in formatDate

Coverage Goals

> What would it take to get auth.js to 80% coverage?

Common Testing Scenarios

Async Functions

> Write tests for this async function that fetches user data

Claude handles: - async/await - Promises - Mocking fetch calls

Error Handling

> Add tests that verify the function throws correct errors

Edge Cases

> What edge cases should I test for parsePhoneNumber?

Claude suggests: - Empty input - Invalid formats - International numbers - Special characters

Mocking

> Write tests for sendEmail that mock the email service

Framework-Specific Help

Jest

> Set up Jest for this project

> How do I mock a module in Jest?

> Use Jest snapshots to test the Header component

Pytest

> Use pytest fixtures for database setup

> How do I parametrize this test?

React Testing Library

> Test that clicking the button triggers the callback

> Test that the loading state shows a spinner

Test Maintenance

Update Tests After Changes

> I changed the User model to include 'role'. Update the tests.

Remove Obsolete Tests

> Which tests are for deleted functionality?

Improve Test Quality

> Review the auth tests for flakiness and bad practices

Try It Yourself

Exercise: Test-Driven Development

  1. Start Claude Code in a new directory
  2. Write tests first:
    > Write tests for a function called `isPrime` that:
      - Returns true for prime numbers (2, 3, 5, 7, 11)
      - Returns false for non-primes (1, 4, 6, 8, 9, 10)
      - Throws for negative numbers and non-integers
    
  3. Run tests (they fail):
    > Run the tests
    
  4. Implement the function:
    > Implement isPrime to pass the tests
    
  5. Run again:
    > Run the tests
    

Exercise: Coverage Challenge

  1. Take an existing file with low coverage
  2. Ask Claude what's not tested:
    > What code paths in auth.js have no tests?
    
  3. Write tests for uncovered paths
  4. Verify coverage improved

Pro Tips

Test Names Matter

> Rename these tests to describe the behavior being tested,
  not just the function name

Avoid Testing Implementation

> This test is brittle because it tests implementation details.
  Rewrite it to test behavior.

One Assertion Per Test

> Split this test into multiple tests, one for each assertion

Use Before/After Hooks

> Set up common test fixtures using beforeEach

What's Next?

You've completed intermediate tutorials! Move on to Advanced: Custom Commands to extend Claude Code.


Summary: - Claude can run tests and interpret results - Generate tests based on code analysis or specifications - Support for TDD: write tests first, then implement - Debugging failing tests by analyzing expected vs actual - Coverage analysis and improvement suggestions


Learning Resources

GitHub: TDD with GitHub Copilot (Official GitHub channel)

Test-Driven Development with AI - write tests first, implement, verify with AI assistance.

Additional Resources

Type Resource Description
🎬 Video Claude Code Testing Tips Edmund Yong - TDD workflows
📚 Official Docs GitHub TDD Guide Official TDD documentation
📖 Tutorial TDD with AI Builder.io AI TDD patterns
🎓 Free Course Microsoft TDD Course Free paired programming course
💼 Commercial TDD Complete Course Comprehensive TDD training