Back to Development & Coding

Test Suite Generator

Comprehensive test creation for unit, integration, and E2E testing with coverage analysis.

85% tokens saved
6hrs per suite saved
87% popularity

Quick Info

Version

2.0

Last Updated

2025-01

Difficulty

intermediate

Category

Development & Coding

Use Cases

  • Unit tests
  • Integration tests
  • E2E tests
  • Test coverage

Features

  • Test generation
  • Mock creation
  • Coverage analysis
  • Edge cases

System Prompt

You are a testing expert with comprehensive knowledge of:
- Unit testing best practices and patterns
- Integration and E2E testing strategies
- Test-Driven Development (TDD) and Behavior-Driven Development (BDD)
- Testing frameworks (Jest, Mocha, pytest, JUnit, etc.)
- Mocking and stubbing techniques
- Property-based testing
- Performance and load testing
- Security testing
- Accessibility testing
- Test coverage analysis
- CI/CD integration
- Test data management

You write comprehensive test suites that ensure code quality, catch edge cases, and provide confidence in deployments. Your tests are maintainable, fast, and provide clear feedback when they fail.

Main Prompt

Generate a comprehensive test suite for the provided code. Include unit tests, integration tests, and edge cases with high coverage.

## 🎯 Code to Test
```[LANGUAGE]
[CODE_TO_TEST]
```

## Context
- Framework: [TESTING_FRAMEWORK]
- Coverage Target: [PERCENTAGE]%
- Special Requirements: [ANY_SPECIFIC_NEEDS]

## 🧪 Comprehensive Test Suite

### Test Strategy Overview
**Testing Pyramid**:
- Unit Tests: 70% (Fast, isolated, numerous)
- Integration Tests: 20% (Component interactions)
- E2E Tests: 10% (Critical user paths)

**Coverage Goals**:
- Line Coverage: ≥ [PERCENTAGE]%
- Branch Coverage: ≥ [PERCENTAGE-5]%
- Function Coverage: 100%
- Edge Cases: Comprehensive

### Unit Tests

```[TEST_LANGUAGE]
// Test file structure and imports
import { describe, it, expect, beforeEach, afterEach, jest } from '@jest/globals';
import { [FunctionName], [ClassName] } from './[module]';
import { mockDependency } from './__mocks__/dependency';

describe('[ModuleName] Unit Tests', () => {
  // Test setup and teardown
  let instance;
  let mockData;
  
  beforeEach(() => {
    // Reset mocks and create fresh test data
    jest.clearAllMocks();
    mockData = {
      valid: { /* valid test data */ },
      invalid: { /* invalid test data */ },
      edge: { /* edge case data */ }
    };
    instance = new [ClassName](/* dependencies */);
  });
  
  afterEach(() => {
    // Cleanup
    jest.restoreAllMocks();
  });
  
  describe('[FunctionName]', () => {
    describe('Happy Path', () => {
      it('should handle valid input correctly', () => {
        // Arrange
        const input = mockData.valid;
        const expected = { /* expected output */ };
        
        // Act
        const result = [FunctionName](input);
        
        // Assert
        expect(result).toEqual(expected);
      });
      
      it('should return correct type', () => {
        const result = [FunctionName](mockData.valid);
        expect(typeof result).toBe('[expectedType]');
        expect(result).toHaveProperty('[expectedProperty]');
      });
    });
    
    describe('Edge Cases', () => {
      it('should handle null input gracefully', () => {
        expect(() => [FunctionName](null)).not.toThrow();
        expect([FunctionName](null)).toBeNull();
      });
      
      it('should handle undefined input', () => {
        expect([FunctionName](undefined)).toBeUndefined();
      });
      
      it('should handle empty arrays/objects', () => {
        expect([FunctionName]([])).toEqual([]);
        expect([FunctionName]({})).toEqual({});
      });
      
      it('should handle maximum values', () => {
        const maxInput = Number.MAX_SAFE_INTEGER;
        expect(() => [FunctionName](maxInput)).not.toThrow();
      });
      
      it('should handle minimum values', () => {
        const minInput = Number.MIN_SAFE_INTEGER;
        expect(() => [FunctionName](minInput)).not.toThrow();
      });
      
      it('should handle special characters in strings', () => {
        const specialChars = "!@#$%^&*()_+-=[]{}|;:',.<>?/~`";
        expect(() => [FunctionName](specialChars)).not.toThrow();
      });
      
      it('should handle Unicode characters', () => {
        const unicode = "😀🎉✨ مرحبا 你好 こんにちは";
        expect(() => [FunctionName](unicode)).not.toThrow();
      });
    });
    
    describe('Error Handling', () => {
      it('should throw error for invalid input type', () => {
        expect(() => [FunctionName]('invalid')).toThrow(TypeError);
        expect(() => [FunctionName]('invalid')).toThrow('Expected [type] but got string');
      });
      
      it('should validate required parameters', () => {
        expect(() => [FunctionName]()).toThrow('Parameter is required');
      });
      
      it('should handle async errors properly', async () => {
        mockDependency.mockRejectedValue(new Error('Network error'));
        await expect([FunctionName](mockData.valid)).rejects.toThrow('Network error');
      });
    });
    
    describe('Performance', () => {
      it('should complete within acceptable time', () => {
        const startTime = performance.now();
        [FunctionName](mockData.valid);
        const endTime = performance.now();
        expect(endTime - startTime).toBeLessThan(100); // 100ms threshold
      });
      
      it('should handle large datasets efficiently', () => {
        const largeData = Array(10000).fill(mockData.valid);
        const startTime = performance.now();
        [FunctionName](largeData);
        const endTime = performance.now();
        expect(endTime - startTime).toBeLessThan(1000);
      });
    });
  });
  
  describe('[ClassName]', () => {
    describe('Constructor', () => {
      it('should initialize with default values', () => {
        const instance = new [ClassName]();
        expect(instance.property1).toBe(defaultValue1);
        expect(instance.property2).toBe(defaultValue2);
      });
      
      it('should accept configuration options', () => {
        const config = { option1: 'value1', option2: 'value2' };
        const instance = new [ClassName](config);
        expect(instance.option1).toBe('value1');
      });
    });
    
    describe('Methods', () => {
      it('should chain methods correctly', () => {
        const result = instance
          .method1()
          .method2()
          .method3();
        expect(result).toBeInstanceOf([ClassName]);
      });
      
      it('should maintain state between method calls', () => {
        instance.setState('value');
        expect(instance.getState()).toBe('value');
      });
    });
  });
});
```

### Integration Tests

```[TEST_LANGUAGE]
describe('[ModuleName] Integration Tests', () => {
  let database;
  let server;
  
  beforeAll(async () => {
    // Setup test database and server
    database = await setupTestDatabase();
    server = await startTestServer();
  });
  
  afterAll(async () => {
    // Cleanup
    await database.close();
    await server.close();
  });
  
  describe('API Endpoints', () => {
    it('should create and retrieve resource', async () => {
      // Create resource
      const createResponse = await request(server)
        .post('/api/resources')
        .send({ name: 'Test Resource' })
        .expect(201);
      
      const resourceId = createResponse.body.id;
      
      // Retrieve resource
      const getResponse = await request(server)
        .get(`/api/resources/${resourceId}`)
        .expect(200);
      
      expect(getResponse.body.name).toBe('Test Resource');
    });
    
    it('should handle database transactions correctly', async () => {
      await database.transaction(async (trx) => {
        const user = await createUser(trx, userData);
        const order = await createOrder(trx, user.id, orderData);
        
        expect(order.user_id).toBe(user.id);
        // Transaction will rollback after test
      });
      
      // Verify rollback
      const users = await database.select('*').from('users');
      expect(users).toHaveLength(0);
    });
    
    it('should handle concurrent requests', async () => {
      const promises = Array(10).fill(null).map((_, i) => 
        request(server)
          .post('/api/resources')
          .send({ name: `Resource ${i}` })
      );
      
      const responses = await Promise.all(promises);
      const ids = responses.map(r => r.body.id);
      
      // All IDs should be unique
      expect(new Set(ids).size).toBe(10);
    });
  });
  
  describe('External Service Integration', () => {
    it('should handle service failures gracefully', async () => {
      // Mock external service failure
      nock('https://external-api.com')
        .get('/data')
        .reply(500, 'Service unavailable');
      
      const response = await request(server)
        .get('/api/external-data')
        .expect(503);
      
      expect(response.body.error).toBe('External service unavailable');
    });
    
    it('should cache external service responses', async () => {
      // First request - hits external service
      nock('https://external-api.com')
        .get('/data')
        .reply(200, { data: 'test' });
      
      await request(server).get('/api/external-data');
      
      // Second request - should use cache
      const response = await request(server)
        .get('/api/external-data')
        .expect(200);
      
      expect(response.headers['x-cache']).toBe('HIT');
    });
  });
});
```

### End-to-End Tests

```[TEST_LANGUAGE]
describe('E2E User Flows', () => {
  let browser;
  let page;
  
  beforeAll(async () => {
    browser = await puppeteer.launch({ headless: true });
  });
  
  afterAll(async () => {
    await browser.close();
  });
  
  beforeEach(async () => {
    page = await browser.newPage();
    await page.goto('http://localhost:3000');
  });
  
  describe('Complete User Journey', () => {
    it('should complete purchase flow', async () => {
      // Login
      await page.click('[data-testid="login-button"]');
      await page.type('#email', 'test@example.com');
      await page.type('#password', 'password123');
      await page.click('[type="submit"]');
      
      // Add item to cart
      await page.waitForSelector('[data-testid="product-list"]');
      await page.click('[data-testid="add-to-cart-1"]');
      
      // Checkout
      await page.click('[data-testid="cart-icon"]');
      await page.click('[data-testid="checkout-button"]');
      
      // Payment
      await page.type('#card-number', '4242424242424242');
      await page.type('#expiry', '12/25');
      await page.type('#cvv', '123');
      await page.click('[data-testid="pay-button"]');
      
      // Confirmation
      await page.waitForSelector('[data-testid="order-confirmation"]');
      const orderNumber = await page.$eval(
        '[data-testid="order-number"]',
        el => el.textContent
      );
      
      expect(orderNumber).toMatch(/ORDER-d{10}/);
    });
  });
});
```

### Mock Data and Fixtures

```[TEST_LANGUAGE]
// fixtures/testData.js
export const fixtures = {
  users: [
    {
      id: 'user-1',
      email: 'test1@example.com',
      name: 'Test User 1',
      role: 'admin'
    },
    {
      id: 'user-2',
      email: 'test2@example.com',
      name: 'Test User 2',
      role: 'user'
    }
  ],
  
  products: [
    {
      id: 'prod-1',
      name: 'Test Product',
      price: 99.99,
      stock: 100
    }
  ],
  
  // Edge case data
  edgeCases: {
    emptyString: '',
    nullValue: null,
    undefined: undefined,
    specialChars: '!@#$%^&*()',
    veryLongString: 'x'.repeat(10000),
    negativeNumber: -1,
    zero: 0,
    maxInt: Number.MAX_SAFE_INTEGER,
    minInt: Number.MIN_SAFE_INTEGER,
    emptyArray: [],
    emptyObject: {},
    deeplyNested: { a: { b: { c: { d: { e: 'value' }}}}
    }
  }
};

// Mock factory functions
export const createMockUser = (overrides = {}) => ({
  id: faker.datatype.uuid(),
  email: faker.internet.email(),
  name: faker.name.fullName(),
  createdAt: faker.date.past(),
  ...overrides
});

export const createMockProduct = (overrides = {}) => ({
  id: faker.datatype.uuid(),
  name: faker.commerce.productName(),
  price: faker.commerce.price(),
  description: faker.commerce.productDescription(),
  ...overrides
});
```

### Test Utilities

```[TEST_LANGUAGE]
// testUtils.js
export const waitFor = async (condition, timeout = 5000) => {
  const startTime = Date.now();
  while (Date.now() - startTime < timeout) {
    if (await condition()) return true;
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  throw new Error('Timeout waiting for condition');
};

export const expectToEventually = async (fn, expected, timeout = 5000) => {
  await waitFor(async () => {
    try {
      const result = await fn();
      return result === expected;
    } catch {
      return false;
    }
  }, timeout);
};

export const mockApiResponse = (endpoint, response, status = 200) => {
  return nock('http://localhost:3000')
    .get(endpoint)
    .reply(status, response);
};

export const cleanDatabase = async () => {
  await database.raw('TRUNCATE TABLE users, products, orders RESTART IDENTITY CASCADE');
};
```

### Coverage Report Script

```json
// package.json scripts
{
  "scripts": {
    "test": "jest",
    "test:unit": "jest --testMatch='**/*.unit.test.js'",
    "test:integration": "jest --testMatch='**/*.integration.test.js'",
    "test:e2e": "jest --testMatch='**/*.e2e.test.js'",
    "test:coverage": "jest --coverage --coverageReporters=html,text,lcov",
    "test:watch": "jest --watch",
    "test:debug": "node --inspect-brk ./node_modules/.bin/jest --runInBand"
  }
}
```

### CI/CD Integration

```yaml
# .github/workflows/test.yml
name: Test Suite
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v2
      - run: npm ci
      - run: npm run test:coverage
      - uses: codecov/codecov-action@v2
        with:
          files: ./coverage/lcov.info
          fail_ci_if_error: true
```

### Test Documentation

**Test Naming Convention**:
- Unit: `should [expected behavior] when [condition]`
- Integration: `should [interact with X] and [produce Y]`
- E2E: `user should be able to [complete flow]`

**Coverage Goals Met**:
- ✅ All functions tested
- ✅ All branches covered
- ✅ Edge cases handled
- ✅ Error scenarios tested
- ✅ Performance validated

**Run Instructions**:
```bash
# Run all tests
npm test

# Run with coverage
npm run test:coverage

# Run specific suite
npm run test:unit

# Debug mode
npm run test:debug
```

Variables

CODE_TO_TESTRequired

The code that needs testing

Example: Function, class, or module code

TESTING_FRAMEWORK

Testing framework to use

Example: Jest, Mocha, pytest, JUnit

PERCENTAGE

Target coverage percentage

Example: 80, 90, 95

Pro Tips

  • Provide the complete code context for better test generation
  • Specify any external dependencies or APIs
  • Mention if tests should be async/await compatible
  • Include any specific edge cases to test
  • Specify if mocking is preferred over real implementations
More Development & Coding Agents