10 Prompts for Writing Unit and Integration Tests (pytest, Jest, unittest)
Writing tests is essential for reliable software, but getting started can be slow. Using targeted prompts with AI tools like ChatGPT or GitHub Copilot can speed up test generation while maintaining quality. Below are 10 actionable prompts for Python (pytest, unittest) and JavaScript (Jest) testing. Each prompt is ready to copy, paste, and adapt.
1. Basic pytest unit tests for a function
Task: Generate tests for a pure function.
Prompt:
"Write pytest tests for this function. Cover normal input, edge cases (empty, negative, large numbers), and type errors. Use descriptive test names:
def test_<scenario>()."
Example function:
def add(a, b):
return a + b
Generated tests:
def test_add_positive():
assert add(2, 3) == 5
def test_add_negative():
assert add(-1, -1) == -2
def test_add_float():
assert add(0.1, 0.2) == pytest.approx(0.3)
Reference: Official pytest guide (docs.pytest.org) recommends using pytest.approx for floats.
2. pytest parameterized tests
Task: Reduce boilerplate with many similar test cases.
Prompt:
"Refactor these tests into a single parameterized pytest test using
@pytest.mark.parametrize."
Example input cases: (2,3,5), (0,0,0), (-1,1,0), (100,-100,0).
Generated code:
import pytest
@pytest.mark.parametrize("a,b,expected", [
(2,3,5), (0,0,0), (-1,1,0), (100,-100,0)
])
def test_add(a, b, expected):
assert add(a, b) == expected
3. pytest mock external API call
Task: Test code that calls an external HTTP endpoint without network.
Prompt:
"Using pytest and
unittest.mock, write a test that mocksrequests.getfor this function. Test both success and HTTP error responses."
Example function:
import requests
def get_user(user_id):
resp = requests.get(f"https://api.example.com/users/{user_id}")
return resp.json()
Generated test:
from unittest.mock import patch
def test_get_user_success(mocker):
mock_response = mocker.Mock(status_code=200)
mock_response.json.return_value = {"id": 1, "name": "Alice"}
mocker.patch("requests.get", return_value=mock_response)
assert get_user(1)["name"] == "Alice"
4. pytest fixture for database connection
Task: Set up a temporary in‑memory SQLite database for tests.
Prompt:
"Create a pytest fixture that provides a fresh SQLite in‑memory database with a
userstable. Write two tests: one that inserts a user and one that reads it."
Generated fixture:
import sqlite3
import pytest
@pytest.fixture
def db():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)")
yield conn
conn.close()
5. Jest unit tests for a React component
Task: Test a simple component rendering and interaction.
Prompt:
"Using Jest and Testing Library, write tests for this React button component. Test that it renders the label, fires the onClick, and shows disabled state."
Example component:
function MyButton({ label, onClick, disabled }) {
return ;
}
Generated test:
import { render, fireEvent } from '@testing-library/react';
test('calls onClick when clicked', () => {
const handleClick = jest.fn();
const { getByText } = render(
fireEvent.click(getByText('Click'));
expect(handleClick).toHaveBeenCalledTimes(1);
});
Reference: Official Jest documentation (jestjs.io) and Testing Library (testing-library.com).
6. Jest async tests with mocking
Task: Test an async function that fetches data.
Prompt:
"Write a Jest test using
jest.fn()to mockfetch. Test resolved and rejected promise scenarios."
Example function:
async function getUser(id) {
const response = await fetch(/api/users/${id});
return response.json();
}
Generated test:
global.fetch = jest.fn(() =>
Promise.resolve({ json: () => Promise.resolve({ name: 'Bob' }) })
);
test('returns user name', async () => {
const user = await getUser(1);
expect(user.name).toBe('Bob');
});
7. Jest snapshot tests
Task: Catch unintended UI changes.
Prompt:
"Create a Jest snapshot test for this component. Update snapshot file if changes are intentional."
Generated test:
import renderer from 'react-test-renderer';
test('matches snapshot', () => {
const tree = renderer.create(
expect(tree).toMatchSnapshot();
});
8. unittest basic test class
Task: Structure tests using Python’s built‑in unittest.
Prompt:
"Using
unittest.TestCase, write a test class for a simple calculator with methods:add,subtract,multiply,divide. IncludesetUpto create an instance."
Generated code:
import unittest
class TestCalculator(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_add(self):
self.assertEqual(self.calc.add(2,3), 5)
def test_divide_by_zero(self):
with self.assertRaises(ZeroDivisionError):
self.calc.divide(1,0)
9. unittest mock and patch
Task: Replace a dependency in a unittest.
Prompt:
"Using
unittest.mock.patch, mock thetime.sleepcall in this function to avoid delays."
Example function:
import time
def process():
time.sleep(10)
return "done"
Generated test:
from unittest.mock import patch
def test_process_skips_sleep(self):
with patch('time.sleep') as mock_sleep:
result = process()
mock_sleep.assert_called_once_with(10)
self.assertEqual(result, "done")
10. Integration test with pytest and FastAPI
Task: Test a FastAPI endpoint end‑to‑end.
Prompt:
"Using
TestClientfrom FastAPI, write a test that sends a POST request to/itemsand checks the response status and body. Include a test for invalid input."
Generated test:
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_create_item():
response = client.post("/items", json={"name": "Foo"})
assert response.status_code == 201
assert response.json()["name"] == "Foo"
Reference: FastAPI testing docs (fastapi.tiangolo.com/tutorial/testing/).
Conclusion
These 10 prompts cover the most common testing scenarios for Python and JavaScript projects. Copy them into your AI assistant, adapt the function/component names, and you’ll have a solid test suite in minutes. Remember to run tests locally and review generated code — AI can miss project‑specific nuances. Happy testing!
Comments