Why a Prompt Collection for Tests?
Writing tests is one of the most undervalued skills in software engineering. According to the 2023 Stack Overflow Developer Survey, only about 40% of professional developers write tests regularly. Yet, teams that adopt test-driven development (TDD) report up to 40% fewer production defects, as shown in a study by Nagappan et al. at Microsoft Research. The challenge isn't motivation—it's knowing how to generate meaningful test cases efficiently.
This article collects 18 structured prompts designed to help you generate unit and integration tests using three major frameworks: pytest (Python), Jest (JavaScript/TypeScript), and unittest (Python). Each prompt is a complete task with an example result, so you can copy, adapt, and apply them directly to your codebase.
Basic Prompts (Beginner Level)
1. Generate a Unit Test for a Pure Function
Task: Create a pytest unit test for a function that adds two numbers and returns the result.
Prompt: "Write a pytest test for the function add(a, b) that returns a + b. Include tests for positive numbers, negative numbers, zero, and edge cases like very large integers."
Example Result:
import pytest
def add(a, b):
return a + b
class TestAdd:
def test_positive_numbers(self):
assert add(2, 3) == 5
def test_negative_numbers(self):
assert add(-1, -2) == -3
def test_with_zero(self):
assert add(0, 5) == 5
assert add(5, 0) == 5
def test_large_numbers(self):
assert add(10**9, 10**9) == 2 * 10**9
2. Generate a Jest Unit Test for a String Utility
Task: Write a Jest test for a function that reverses a string.
Prompt: "Provide a Jest test suite for reverseString(str) that handles normal strings, empty strings, single characters, and palindromes."
Example Result:
function reverseString(str) {
return str.split('').reverse().join('');
}
describe('reverseString', () => {
test('reverses a normal string', () => {
expect(reverseString('hello')).toBe('olleh');
});
test('returns empty string for empty input', () => {
expect(reverseString('')).toBe('');
});
test('handles single character', () => {
expect(reverseString('a')).toBe('a');
});
test('palindrome remains same', () => {
expect(reverseString('racecar')).toBe('racecar');
});
});
3. Generate a unittest Test for a Class Method
Task: Create a unittest test case for a BankAccount class with deposit and withdraw methods.
Prompt: "Write a unittest.TestCase for a BankAccount class that validates deposit increases balance, withdraw decreases balance, and insufficient funds raise an exception."
Example Result:
import unittest
class BankAccount:
def __init__(self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit amount must be positive")
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("Insufficient funds")
self.balance -= amount
class TestBankAccount(unittest.TestCase):
def setUp(self):
self.account = BankAccount(100)
def test_initial_balance(self):
self.assertEqual(self.account.balance, 100)
def test_deposit_increases_balance(self):
self.account.deposit(50)
self.assertEqual(self.account.balance, 150)
def test_withdraw_decreases_balance(self):
self.account.withdraw(30)
self.assertEqual(self.account.balance, 70)
def test_withdraw_insufficient_funds(self):
with self.assertRaises(ValueError):
self.account.withdraw(200)
if __name__ == '__main__':
unittest.main()
Advanced Prompts (Intermediate Level)
4. Generate pytest Fixtures for Database Connection
Task: Write a pytest fixture that sets up a temporary SQLite database and tears it down after each test.
Prompt: "Create a pytest fixture that provides an in-memory SQLite database with a 'users' table. The fixture should create the table before each test and drop it after."
Example Result:
import pytest
import sqlite3
@pytest.fixture
def db():
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()
cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)')
yield conn
conn.close()
def test_insert_user(db):
cursor = db.cursor()
cursor.execute('INSERT INTO users (name) VALUES (?)', ('Alice',))
db.commit()
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()
assert len(users) == 1
assert users[0][1] == 'Alice'
5. Generate Jest Mocks for API Calls
Task: Write a Jest test that mocks an Axios GET request to an external API.
Prompt: "Provide a Jest test for a function fetchUser(id) that uses axios.get. Mock the axios call to return a fake user object, and verify the function returns the expected data."
Example Result:
import axios from 'axios';
import { fetchUser } from './api';
jest.mock('axios');
describe('fetchUser', () => {
it('fetches user data successfully', async () => {
const fakeUser = { id: 1, name: 'John Doe' };
axios.get.mockResolvedValue({ data: fakeUser });
const result = await fetchUser(1);
expect(result).toEqual(fakeUser);
expect(axios.get).toHaveBeenCalledWith('/users/1');
});
it('handles network error', async () => {
axios.get.mockRejectedValue(new Error('Network Error'));
await expect(fetchUser(1)).rejects.toThrow('Network Error');
});
});
6. Generate unittest with Mock and Patch
Task: Write a unittest test that uses unittest.mock.patch to replace a function that sends an email.
Prompt: "Create a test for a send_welcome_email(user_email) function that internally calls send_mail(). Use mock.patch to verify send_mail was called with correct arguments."
Example Result:
from unittest import TestCase
from unittest.mock import patch
from myapp.email import send_welcome_email
class TestWelcomeEmail(TestCase):
@patch('myapp.email.send_mail')
def test_sends_email_with_correct_args(self, mock_send_mail):
send_welcome_email('user@example.com')
mock_send_mail.assert_called_once_with(
'Welcome!',
'Thank you for signing up.',
'noreply@example.com',
['user@example.com']
)
7. Generate pytest Parameterized Tests
Task: Write a parameterized test using @pytest.mark.parametrize to test a function that checks if a number is prime.
Prompt: "Create a parametrized pytest test for is_prime(n) that covers primes, non-primes, one, zero, and negative numbers."
Example Result:
import pytest
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
@pytest.mark.parametrize('n, expected', [
(2, True),
(3, True),
(4, False),
(1, False),
(0, False),
(-5, False),
(17, True),
(25, False),
])
def test_is_prime(n, expected):
assert is_prime(n) == expected
8. Generate Jest Test for Async Functions
Task: Write a Jest test for an async function that fetches data from multiple endpoints.
Prompt: "Test an async function getUserAndPosts(userId) that returns both user info and their posts using Promise.all. Use mock implementations for both API calls."
Example Result:
import { getUserAndPosts } from './api';
import axios from 'axios';
jest.mock('axios');
describe('getUserAndPosts', () => {
it('returns user and posts', async () => {
const user = { id: 1, name: 'Alice' };
const posts = [{ id: 1, title: 'Post 1' }];
axios.get.mockImplementation((url) => {
if (url.includes('/users/1')) return Promise.resolve({ data: user });
if (url.includes('/users/1/posts')) return Promise.resolve({ data: posts });
return Promise.reject(new Error('Unknown URL'));
});
const result = await getUserAndPosts(1);
expect(result).toEqual({ user, posts });
});
});
9. Generate unittest for Context Managers
Task: Write a unittest test for a custom context manager that opens and closes a file.
Prompt: "Create a test for a ManagedFile class that implements __enter__ and __exit__. Verify that the file is opened in the context and closed after exit."
Example Result:
import unittest
from unittest.mock import mock_open, patch
class ManagedFile:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'w')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
class TestManagedFile(unittest.TestCase):
@patch('builtins.open', new_callable=mock_open)
def test_file_opened_and_closed(self, mock_file):
with ManagedFile('test.txt') as f:
f.write('hello')
mock_file.assert_called_once_with('test.txt', 'w')
mock_file().close.assert_called_once()
if __name__ == '__main__':
unittest.main()
Expert Prompts (Integration & Advanced Patterns)
10. Generate pytest Integration Test with Docker
Task: Write a pytest integration test that runs a PostgreSQL database in a Docker container using testcontainers.
Prompt: "Create a pytest integration test using the pytest-postgresql plugin or testcontainers to spin up a PostgreSQL container, insert a record, and verify it exists."
Example Result:
import pytest
from testcontainers.postgres import PostgresContainer
import psycopg2
@pytest.fixture(scope='module')
def postgres_container():
with PostgresContainer('postgres:13') as postgres:
yield postgres
def test_insert_and_retrieve(postgres_container):
conn = psycopg2.connect(
host=postgres_container.get_container_host_ip(),
port=postgres_container.get_exposed_port(5432),
user='test',
password='test',
dbname='test'
)
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS items (id SERIAL PRIMARY KEY, name TEXT)')
cur.execute('INSERT INTO items (name) VALUES (%s)', ('Widget',))
conn.commit()
cur.execute('SELECT * FROM items')
assert cur.fetchone()[1] == 'Widget'
cur.close()
conn.close()
11. Generate Jest Test with Snapshot Testing
Task: Write a Jest snapshot test for a React component that renders a user profile.
Prompt: "Create a Jest snapshot test for a React component UserProfile that takes name and email props. Include a test for when props change."
Example Result:
import React from 'react';
import renderer from 'react-test-renderer';
import UserProfile from './UserProfile';
describe('UserProfile snapshot', () => {
it('renders correctly with given props', () => {
const tree = renderer.create(
<UserProfile name="Alice" email="alice@example.com" />
).toJSON();
expect(tree).toMatchSnapshot();
});
it('updates snapshot when props change', () => {
const tree = renderer.create(
<UserProfile name="Bob" email="bob@example.com" />
).toJSON();
expect(tree).toMatchSnapshot();
});
});
12. Generate pytest Test for Exception Handling
Task: Write a pytest test that verifies a function raises specific exceptions with the correct message.
Prompt: "Test a function divide(a, b) that raises ZeroDivisionError with message 'Cannot divide by zero' when b is zero, and TypeError for non-numeric inputs."
Example Result:
import pytest
def divide(a, b):
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
raise TypeError('Both arguments must be numbers')
if b == 0:
raise ZeroDivisionError('Cannot divide by zero')
return a / b
class TestDivide:
def test_division_by_zero(self):
with pytest.raises(ZeroDivisionError, match='Cannot divide by zero'):
divide(10, 0)
def test_non_numeric_input(self):
with pytest.raises(TypeError, match='Both arguments must be numbers'):
divide('a', 5)
def test_valid_division(self):
assert divide(10, 2) == 5
13. Generate Jest Test with Timer Mocks
Task: Write a Jest test that uses fake timers to test a debounced function.
Prompt: "Create a Jest test for a debounce(fn, delay) function. Use jest.useFakeTimers() to verify the function is called only once after the delay."
Example Result:
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
describe('debounce', () => {
jest.useFakeTimers();
it('calls function after delay', () => {
const mockFn = jest.fn();
const debouncedFn = debounce(mockFn, 1000);
debouncedFn();
expect(mockFn).not.toBeCalled();
jest.advanceTimersByTime(1000);
expect(mockFn).toBeCalledTimes(1);
});
it('calls only once on rapid invocations', () => {
const mockFn = jest.fn();
const debouncedFn = debounce(mockFn, 500);
debouncedFn();
debouncedFn();
debouncedFn();
jest.advanceTimersByTime(500);
expect(mockFn).toBeCalledTimes(1);
});
});
14. Generate pytest Test for File I/O
Task: Write a pytest test that uses tmp_path fixture to test a function that writes to a file.
Prompt: "Create a pytest test for save_to_file(filename, content) that writes content to a file. Use the built-in tmp_path fixture to create temporary files."
Example Result:
import pytest
def save_to_file(filename, content):
with open(filename, 'w') as f:
f.write(content)
def test_save_to_file(tmp_path):
d = tmp_path / 'sub'
d.mkdir()
file_path = d / 'test.txt'
save_to_file(file_path, 'Hello, World!')
assert file_path.read_text() == 'Hello, World!'
15. Generate Jest Test for Custom Hooks
Task: Write a Jest test for a custom React hook useLocalStorage that stores and retrieves values from localStorage.
Prompt: "Create a Jest test for a custom hook useLocalStorage(key, initialValue). Mock localStorage and test that the hook returns the stored value and updates it correctly."
Example Result:
import { renderHook, act } from '@testing-library/react';
import { useLocalStorage } from './useLocalStorage';
describe('useLocalStorage', () => {
beforeEach(() => {
localStorage.clear();
});
it('returns initial value when no stored value', () => {
const { result } = renderHook(() => useLocalStorage('test', 'default'));
expect(result.current[0]).toBe('default');
});
it('stores and retrieves a value', () => {
const { result } = renderHook(() => useLocalStorage('test', ''));
act(() => {
result.current[1]('new value');
});
expect(result.current[0]).toBe('new value');
expect(localStorage.getItem('test')).toBe('"new value"');
});
});
16. Generate unittest for Network Requests
Task: Write a unittest test that uses responses library to mock HTTP requests.
Prompt: "Create a unittest test for a function get_weather(city) that calls an API. Use the responses library to mock the HTTP response."
Example Result:
import unittest
import responses
import requests
def get_weather(city):
url = f'https://api.weather.com/v1/city/{city}'
resp = requests.get(url)
return resp.json()
class TestWeatherAPI(unittest.TestCase):
@responses.activate
def test_get_weather_success(self):
responses.add(
responses.GET,
'https://api.weather.com/v1/city/London',
json={'temperature': 15, 'condition': 'Cloudy'},
status=200
)
result = get_weather('London')
self.assertEqual(result['temperature'], 15)
self.assertEqual(result['condition'], 'Cloudy')
if __name__ == '__main__':
unittest.main()
17. Generate pytest Test with Conftest
Task: Write a shared fixture in conftest.py that provides a configured client for a Flask app.
Prompt: "Create a conftest.py file with a pytest fixture that returns a Flask test client. Then write a test that uses it to test an endpoint."
Example Result:
# conftest.py
import pytest
from myapp import create_app
@pytest.fixture
def client():
app = create_app()
app.config['TESTING'] = True
with app.test_client() as client:
yield client
# test_app.py
def test_home_page(client):
response = client.get('/')
assert response.status_code == 200
assert b'Welcome' in response.data
18. Generate Jest Test for Error Boundaries
Task: Write a Jest test for a React Error Boundary component that catches errors and displays a fallback UI.
Prompt: "Create a Jest test for an ErrorBoundary component. Use console.error mock to silence expected errors, and verify that the fallback UI renders when a child throws."
Example Result:
import React from 'react';
import { render, screen } from '@testing-library/react';
import ErrorBoundary from './ErrorBoundary';
const ThrowError = () => {
throw new Error('Test error');
};
describe('ErrorBoundary', () => {
beforeEach(() => {
jest.spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
console.error.mockRestore();
});
it('renders fallback UI when child throws', () => {
render(
<ErrorBoundary fallback={<div>Something went wrong</div>}>
<ThrowError />
</ErrorBoundary>
);
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
});
it('renders children without error', () => {
render(
<ErrorBoundary fallback={<div>Error</div>}>
<div>Normal content</div>
</ErrorBoundary>
);
expect(screen.getByText('Normal content')).toBeInTheDocument();
});
});
Conclusion
These 18 prompts cover the spectrum from basic unit tests to advanced integration scenarios with mocks, fixtures, and external services. By using these prompts as starting points, you can accelerate your test-writing process and build more robust software. Start with the basic prompts to get comfortable, then gradually adopt the advanced patterns as your testing needs grow. The key is consistency—make testing a habit, not an afterthought.
For more resources, refer to the official documentation for pytest, Jest, and unittest. Happy testing!
Comments