Guides

Generating tests with Grok Build

View as Markdown

Grok Build reads your code and generates tests that match your existing patterns. It examines your test files to learn which framework you use, how you structure tests, what mocking approach you prefer, and how you name test cases. The generated tests fit with what you already have.

More importantly, Grok Build can run tests via the terminal and iterate on failures. Generate tests, run them, fix what breaks, run again. This closed loop produces tests that work.

Generating tests for existing code

Agent example: Test a class
Write unit tests for src/services/PaymentProcessor.ts. Cover the happy path and common error cases like invalid card numbers, expired cards, and insufficient funds.
See the agent's response
Read src/services/PaymentProcessor.ts
Searched codebase existing test patterns
Read src/services/__tests__/OrderService.test.ts
Thought for 2s
The codebase uses Jest with mock factories. I'll follow the same pattern - mock Stripe, test happy path first, then error cases.
CreatedPaymentProcessor.test.ts+87
import { PaymentProcessor } from '../PaymentProcessor';
import { mockStripeClient } from '../../test/mocks';

describe('PaymentProcessor', () => {
  describe('processPayment', () => {
    it('charges the card and returns confirmation', async () => {
      // ...
    });

    it('throws InvalidCardError for declined cards', async () => {
      // ...
    });
  });
});
Ran npm test PaymentProcessor
Created 8 tests for PaymentProcessor:
•charges card and returns confirmation
•throws InvalidCardError for declined cards
•throws ExpiredCardError for expired cards
•throws InsufficientFundsError when balance is low
•retries on network timeout (up to 3 times)
•logs payment attempts with correlation ID
•handles partial refunds correctly
•validates currency codes before processing
All tests passing. Used your existing mock factory pattern from OrderService tests.

When specifying what to test, be explicit about the cases that matter:

Agent example: Specify coverage goals
Write tests for src/services/OrderService.ts. Cover: successful orders, insufficient inventory, invalid payment methods, partial refunds, and concurrent order modifications.
See the agent's response
Read src/services/OrderService.ts
Searched codebase OrderService dependencies and error handling
Thought for 2s
OrderService has 5 main flows: create, update inventory, process payment, handle refunds, and concurrent modifications. I'll create focused test suites for each.
CreatedOrderService.test.ts+156
describe('OrderService', () => {
  describe('successful orders', () => {
    it('creates order with valid items and payment', async () => { });
    it('decrements inventory on success', async () => { });
  });

  describe('insufficient inventory', () => {
    it('throws InsufficientStockError when item unavailable', async () => { });
    it('does not charge payment if inventory check fails', async () => { });
  });

  describe('concurrent modifications', () => {
    it('uses optimistic locking to prevent overselling', async () => { });
  });
});
Ran npm test OrderService
Created 12 tests for OrderService covering all requested scenarios:
Successful orders (3 tests)
•Creates order, decrements inventory, sends confirmation
Insufficient inventory (2 tests)
•Throws error, doesn't charge payment
Invalid payment methods (3 tests)
•Expired card, invalid number, declined
Partial refunds (2 tests)
•Partial amount, inventory restoration
Concurrent modifications (2 tests)
•Optimistic locking, retry logic
All tests passing.

Grok Build pulls from your existing tests to match patterns. If you have well-structured test files, the generated tests will follow the same structure, mocking strategies, and naming conventions.

Testing code you did not write

Test generation is useful for understanding unfamiliar code, not only code you wrote yourself. When working with legacy systems or third-party integrations, generating tests forces Grok Build to figure out how the code works, including internal APIs and undocumented behavior.

Agent example: Test unfamiliar code
Generate tests for this legacy integration module. I need to understand what it does before modifying it. Cover the main code paths and document the expected behavior in the test names.
See the agent's response
Read src/integrations/legacy/SAPConnector.ts
Searched codebase SAPConnector usage and dependencies
Thought for 3s
This connector has complex retry logic and transforms data between formats. I'll write tests that document each transformation and the retry behavior.
CreatedSAPConnector.test.ts+124
describe('SAPConnector', () => {
  describe('data transformation', () => {
    it('converts internal Order to SAP BAPI format', () => {
      // Documents the expected field mapping
    });

    it('handles nullable fields in SAP response', () => {
      // SAP returns empty strings for nulls
    });
  });

  describe('retry behavior', () => {
    it('retries on RFC_COMMUNICATION_FAILURE', () => { });
    it('does not retry on RFC_INVALID_PARAMETER', () => { });
  });
});
Generated tests that document the SAPConnector's behavior:
Data Transformation (5 tests)
•Order → BAPI_SALESORDER format
•Customer → KNA1 format
•Null handling (SAP uses empty strings)
•Date format conversion (YYYYMMDD)
•Currency decimal handling
Retry Behavior (3 tests)
•Retries on communication failures (3 attempts)
•No retry on invalid parameters
•Exponential backoff timing
Connection Management (2 tests)
•Pool reuse for same destination
•Timeout after 30 seconds
These tests now serve as documentation. If you need to modify this code, run the tests to verify your understanding.

The tests become executable documentation. If you are inheriting a codebase or working with code from another team, this approach helps you verify your understanding before making changes.

Tests as a safety net for refactoring

Before refactoring, generate tests that lock in current behavior. This gives you confidence that your changes do not break anything.

Agent example: Lock in behavior before refactoring
Generate comprehensive tests for src/services/UserService.ts before I refactor it. I need to preserve all existing behavior. Test every public method and edge case you can find.
See the agent's response
Read src/services/UserService.ts
Searched codebase UserService callers and dependencies
Thought for 2s
UserService has 8 public methods. I need to test each one's current behavior before refactoring. I'll focus on return values and side effects.
CreatedUserService.snapshot.test.ts+198
/**
 * Snapshot tests to lock in current behavior before refactoring.
 * These tests document what the code DOES, not what it SHOULD do.
 */
describe('UserService - Behavior Snapshot', () => {
  describe('getUser', () => {
    it('returns user with profile when exists', async () => { });
    it('returns null when user not found', async () => { });
    it('includes soft-deleted users when flag set', async () => { });
  });

  describe('updateUser', () => {
    it('emits UserUpdated event on success', async () => { });
    it('throws when updating non-existent user', async () => { });
  });
});
Ran npm test UserService.snapshot
Created behavior snapshot tests for UserService:
getUser (4 tests) - Including edge case with soft-deleted users
updateUser (3 tests) - Including event emission
deleteUser (3 tests) - Soft delete vs hard delete
searchUsers (4 tests) - Pagination, filters, sorting
createUser (4 tests) - Validation, duplicate handling
getUsersByOrg (2 tests) - Permission checks
bulkUpdate (3 tests) - Transaction handling
exportUsers (2 tests) - Format options
25 tests passing - current behavior is now documented.
Refactor with confidence. If any test fails, you've changed behavior.

Run these tests after each refactoring step to catch regressions immediately. The tests define what the code should do; as long as they pass, you know the refactoring is safe.

The run-and-fix loop

Enable Auto-run to let Grok Build execute tests automatically. When tests fail, Grok Build reads the output and fixes them:

Agent example: Run and fix loop
Run the tests you just wrote. If any fail, fix the issues and run again until they pass.
See the agent's response
Ran npm test UserService
Thought for 1s
3 tests failing. The mock isn't returning the expected shape - missing the 'profile' relation that the new code expects.
EditedUserService.test.ts+5-2
  const mockUser = { id: '1', email: '[email protected]' };
  const mockUser = {
    id: '1',
    email: '[email protected]',
    profile: { name: 'Test User', avatar: null }
  };
Ran npm test UserService
Fixed. The mock was missing the profile relation that getFullUser() now expects.
All 8 tests passing.

This is faster than reviewing generated tests manually. A test might have an incorrect assertion or miss a setup step. Rather than guessing what is wrong, let Grok Build run the tests and learn from the actual failures.

Tests from requirements

Generate tests directly from acceptance criteria, tickets, or specs. This workflow starts with requirements rather than implementation.

Agent example: Tests from acceptance criteria
Here are the acceptance criteria for the new checkout feature: [paste criteria]. Generate tests that verify each requirement. Don't implement anything yet.
See the agent's response
Thought for 1s
I'll create tests that verify each acceptance criterion without implementing the feature. This gives us a clear spec to build against.
Createdcheckout.spec.ts+65
describe('Checkout Feature', () => {
  describe('Cart Management', () => {
    it('allows adding items to cart', () => {
      // AC: User can add products to cart
    });

    it('persists cart across sessions', () => {
      // AC: Cart contents saved for 7 days
    });
  });

  describe('Payment', () => {
    it('accepts credit cards via Stripe', () => {
      // AC: Support Visa, Mastercard, Amex
    });
  });
});
Generated 12 test cases from your acceptance criteria:
Cart Management (4 tests)
•Adding items, updating quantities, removing items, cart persistence
Shipping (3 tests)
•Address validation, shipping cost calculation, delivery estimates
Payment (5 tests)
•Card processing, error handling, receipt generation, refund support, PCI compliance
All tests are currently failing (not implemented). Build against these to know when you're done.

With MCP integrations, you can pull requirements directly from Jira or other systems and generate tests without copy-pasting. This creates a workflow where tickets become tests before they become code.

Matching your testing patterns

Use rules files to specify your testing conventions so generated tests are consistent with your codebase.

Create a .cursor/rules/testing.mdc file:

Rules example: Testing Conventions

Text

# Testing Conventions

## Framework
- Use Jest with React Testing Library for frontend
- Use pytest with fixtures for backend
- Mock external services, never make real API calls in tests

## Structure
- One test file per source file, named *.test.ts or *_test.py
- Group tests with describe blocks by method or behavior
- Use arrange-act-assert pattern

## Examples to follow
- src/services/__tests__/AuthService.test.ts (good example of service tests)
- src/components/__tests__/Button.test.tsx (good example of component tests)

The "Examples to follow" section matters most. When Grok Build encounters an ambiguous decision, it looks at these files to see how you have handled similar situations.

Integration and E2E tests

Beyond unit tests, Grok Build generates integration and end-to-end tests across frameworks: Playwright, Cypress, Selenium, pytest, Jest, and others. Specify your framework in your rules file.

Agent example: Playwright E2E tests
Generate Playwright tests for the user signup flow. Cover: successful signup, duplicate email error, password too short, and email verification. Follow our existing Playwright patterns.
See the agent's response
Read tests/e2e/playwright.config.ts
Read tests/e2e/auth.setup.ts
Thought for 2s
The project uses Playwright with authenticated state stored in .auth. I'll follow the existing pattern and use the page object model from tests/e2e/pages/.
Createdsignup.spec.ts+87
import { test, expect } from '@playwright/test';
import { SignupPage } from './pages/SignupPage';

test.describe('User Signup Flow', () => {
  test('successful signup with valid data', async ({ page }) => {
    const signup = new SignupPage(page);
    await signup.goto();
    await signup.fillForm({ email: '[email protected]', password: 'SecurePass123!' });
    await signup.submit();
    await expect(page).toHaveURL('/dashboard');
  });

  test('shows error for duplicate email', async ({ page }) => {
    // ...
  });
});
Ran npx playwright test signup.spec.ts
Created 4 Playwright tests for the signup flow:
Successful signup - Valid data → redirects to dashboard
Duplicate email error - Shows 'Email already registered'
Password too short - Client-side validation message
Email verification - Sends email, clicks link, verifies account
Used your existing page object pattern from tests/e2e/pages/. All tests passing in Chromium.

For E2E testing, add rules that specify your automation framework, file locations, and conventions like the page object pattern or test data fixtures.

QA automation workflows

QA teams use Grok Build for test automation beyond what developers typically write. This includes building out regression suites, creating test data generators, and automating manual test cases.

Agent example: Automate manual test
Convert this manual test case into an automated Selenium test: [paste test steps]. Follow our existing automation patterns in tests/e2e/.
See the agent's response
Thought for 2s
This manual test has 12 steps across login, cart, checkout, and confirmation. I'll convert each step to a Selenium action and add assertions at verification points.
Read tests/e2e/base.py
Createdtest_checkout_flow.py+95
import pytest
from selenium.webdriver.common.by import By
from tests.e2e.base import BaseE2ETest

class TestCheckoutFlow(BaseE2ETest):
    """
    Automated from manual test case: TC-CHECKOUT-001
    Original steps documented in test docstrings
    """

    def test_complete_checkout_as_registered_user(self):
        # Step 1: Login with valid credentials
        self.login('[email protected]', 'password123')

        # Step 2: Add product to cart
        self.driver.get(f'{self.base_url}/products/SKU-001')
        self.click(By.ID, 'add-to-cart')

        # Step 3: Verify cart contains item
        self.assert_cart_count(1)
Ran pytest tests/e2e/test_checkout_flow.py -v
Converted manual test TC-CHECKOUT-001 to automated Selenium test:
Steps automated:
1.Login with valid credentials → self.login()
2.Navigate to product → driver.get()
3.Add to cart → click(By.ID, 'add-to-cart')
4.Verify cart badge → assert_cart_count(1)
5.Proceed to checkout → navigation
6.Enter shipping address → form fill
7.Select shipping method → dropdown
8.Enter payment details → Stripe iframe handling
9.Place order → submit
10.Verify confirmation page → assertions
11.Check order in database → API verification
12.Verify confirmation email → mailhog check
Test passing. Added to CI pipeline in .github/workflows/e2e.yml

For QA-specific workflows, create rules files that specify your automation standards, test environments, and reporting requirements.

Requiring tests in code review

Use Bugbot to flag PRs that modify code without adding tests:

Bugbot rules example: Test Coverage Requirements

Text

If the PR modifies files in {server/**, api/**, backend/**} and there are no changes in {**/*.test.*, **/__tests__/**, tests/**}, then:
- Add a blocking Bug titled "Missing tests for backend changes"
- Body: "This PR modifies backend code but includes no accompanying tests."
- Apply label "quality"

This catches missing tests at the source rather than discovering gaps later.

Fixing failing tests in CI

The Grok Build TUI (grok) can fix CI failures, including test failures, from a headless run in your pipeline. See headless scripting for a GitHub Actions workflow that analyzes failures, makes targeted fixes, and creates a fix branch.

Getting started

  1. Start with one file. Pick a file with low coverage and ask Grok Build to generate tests. Review what it produces. Does it match your patterns?

  2. Create a testing rules file. Document your framework, conventions, and point to good examples. This pays off across every test Grok Build generates.

  3. Use the run-and-fix loop. Enable Auto-run and let Grok Build iterate on failures. This produces tests that work.

  4. Review generated tests. Verify they are testing the right things. Check that assertions are meaningful and edge cases are covered.

  5. Add Bugbot rules. Use Bugbot to require tests for code changes so coverage does not slip.


Last updated: November 23, 2026