Guides
Generating tests with Grok Build
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
See the agent's response
Thought for 2s
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 () => {
// ...
});
});
});When specifying what to test, be explicit about the cases that matter:
See the agent's response
Thought for 2s
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 () => { });
});
});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.
See the agent's response
Thought for 3s
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', () => { });
});
});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.
See the agent's response
Thought for 2s
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 () => { });
});
});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:
See the agent's response
Thought for 1s
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 }
};profile relation that getFullUser() now expects.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.
See the agent's response
Thought for 1s
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
});
});
});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:
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.
See the agent's response
Thought for 2s
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 }) => {
// ...
});
});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.
See the agent's response
Thought for 2s
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)self.login()driver.get()click(By.ID, 'add-to-cart')assert_cart_count(1).github/workflows/e2e.ymlFor 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:
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
-
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?
-
Create a testing rules file. Document your framework, conventions, and point to good examples. This pays off across every test Grok Build generates.
-
Use the run-and-fix loop. Enable Auto-run and let Grok Build iterate on failures. This produces tests that work.
-
Review generated tests. Verify they are testing the right things. Check that assertions are meaningful and edge cases are covered.
-
Add Bugbot rules. Use Bugbot to require tests for code changes so coverage does not slip.
Last updated: November 23, 2026