Testing Django + React
By the end of this lesson BookShelf will have two test suites that run in seconds: Django tests that prove the API's rules (permissions, the CSRF-protected login, the throttle, cover uploads) and React tests that prove the screens show the right things and send the right requests. You will see what a failing test looks like, and how to make slow tests fast.
What you should know first: everything up to Media Files & Uploads, plus the basics in the Django course's Testing Flask & Django Apps and the React course's Testing with Vitest. For factories and fixtures in depth, see Testing in Depth: pytest-django & Factories. Versions checked: pytest 9.2.0, pytest-django 4.14.0, Vitest 5.1.0, React Testing Library 16.3.3, user-event 14.6.12, jest-dom 7.0.1 and jsdom 29.1.1.
What to test, and where
A building inspector in Pune checks the foundation, the wiring and the finished flat separately. A crack in the foundation is best found before the walls go up. Tests work the same way.
| Layer | Tool | BookShelf examples | Speed |
|---|---|---|---|
| API rules | Django APITestCase or pytest-django | Readers cannot add books; one review per book; staff-only uploads | Fast |
| Pure functions | Vitest | formatRating, splitErrors | Very fast |
| Components | Vitest + React Testing Library | The review form shows Django's errors in the right place | Fast |
| Whole app in a browser | Playwright (not covered here) | Log in, write a review, see it listed | Slow |
The most valuable tests in this stack sit on the API. Every security rule lives there, and a test proves it holds even when nobody clicks through React. The front-end tests then check that React keeps its side of the contract.
Step 1: API tests with APITestCase
DRF's APITestCase is Django's TestCase with an APIClient: a pretend client that calls your views without a real server. Each test runs inside a database transaction that is rolled back afterwards, so tests cannot disturb each other. Django creates a separate test database and deletes it at the end; your db.sqlite3 is never touched.
Replace books/tests.py. The first part sets up data once for the whole class:
from rest_framework import status
from rest_framework.test import APITestCase
from accounts.models import User
from books.models import Author, Book, Review
class BookShelfTestCase(APITestCase):
"""Fresh data for every test: one author, two books, a staff user and a reader."""
@classmethod
def setUpTestData(cls):
cls.priya = User.objects.create_user("priya", password="test-pass-123", is_staff=True)
cls.kabir = User.objects.create_user("kabir", password="test-pass-123")
narayan = Author.objects.create(name="R. K. Narayan")
cls.swami = Book.objects.create(title="Swami and Friends", author=narayan, published_year=1935)
cls.malgudi = Book.objects.create(title="Malgudi Days", author=narayan, published_year=1943)
cls.priya_review = Review.objects.create(book=cls.swami, user=cls.priya, rating=5)Then tests that read like the rules from earlier lessons:
class ReviewApiTests(BookShelfTestCase):
def test_anonymous_user_cannot_review(self):
response = self.client.post("/api/reviews/", {"book": self.malgudi.id, "rating": 4})
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_review_is_saved_for_the_logged_in_user(self):
self.client.force_authenticate(self.kabir)
response = self.client.post(
"/api/reviews/", {"book": self.malgudi.id, "rating": 4, "user": self.priya.id}
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.data["username"], "kabir") # the "user" field was ignored
def test_second_review_of_same_book_is_rejected(self):
self.client.force_authenticate(self.priya)
response = self.client.post("/api/reviews/", {"book": self.swami.id, "rating": 3})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn("non_field_errors", response.data)
def test_reader_cannot_edit_someone_elses_review(self):
self.client.force_authenticate(self.kabir)
response = self.client.patch(f"/api/reviews/{self.priya_review.id}/", {"rating": 1})
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.data["detail"], "You can only change your own reviews.")setUpTestDataruns once per class, and Django gives each test a fresh copy of the data. Faster than creating users in every test.force_authenticate(user)skips the login and makes every request come from that user. Use it when the test is about permissions, not about logging in.- The second test tries an attack. It sends
"user": priya.idwhile logged in as Kabir, and checks that the review still belongs to Kabir. Good API tests try to break rules, not only follow the happy path.
The full file in our project also has BookApiTests (the list shows averages, ?search=malgudi finds one book, a reader's POST to /api/books/ gets 403).
Step 2: test the real login flow, CSRF included
force_authenticate and the normal test client both skip CSRF checks. That is handy, but it means a broken CSRF setup would pass every test. For the login itself, build a client that enforces CSRF, the way a browser does. Create accounts/tests.py:
from django.core.cache import cache
from rest_framework.test import APIClient, APITestCase
from accounts.models import User
class LoginFlowTests(APITestCase):
"""The real browser flow: CSRF cookie, then login with the X-CSRFToken header."""
@classmethod
def setUpTestData(cls):
User.objects.create_user("kabir", password="test-pass-123")
def setUp(self):
cache.clear() # the login throttle counts attempts in the cache
self.client = APIClient(enforce_csrf_checks=True) # test clients skip CSRF by default
def login(self, password, token=None):
headers = {"X-CSRFToken": token} if token else {}
return self.client.post(
"/api/auth/login/", {"username": "kabir", "password": password}, format="json", headers=headers
)
def test_login_without_csrf_token_is_refused(self):
self.client.get("/api/auth/csrf/")
response = self.login("test-pass-123")
self.assertEqual(response.status_code, 403)
self.assertEqual(response.data["detail"], "CSRF Failed: CSRF token missing.")
def test_login_with_csrf_token_starts_a_session(self):
token = self.client.get("/api/auth/csrf/").cookies["csrftoken"].value
response = self.login("test-pass-123", token)
self.assertEqual(response.status_code, 200)
self.assertTrue(response.cookies["sessionid"]["httponly"])
self.assertEqual(self.client.get("/api/auth/me/").data["username"], "kabir")
def test_sixth_attempt_in_a_minute_is_throttled(self):
token = self.client.get("/api/auth/csrf/").cookies["csrftoken"].value
codes = [self.login("wrong", token).status_code for _ in range(6)]
self.assertEqual(codes, [400, 400, 400, 400, 400, 429])cache.clear() matters. The throttle stores its counts in Django's cache, and the cache is not rolled back between tests like the database. Without it, the throttle test could be affected by login attempts from earlier tests. Our file also checks that a wrong password returns exactly {"detail": "Wrong username or password."}.
Step 3: test uploads without touching real files
Upload tests must not write into the real media folder. override_settings points MEDIA_ROOT at a temporary folder, and Pillow makes a real image in memory. Add to books/tests.py (with the imports shutil, tempfile, BytesIO, SimpleUploadedFile, override_settings and from PIL import Image):
def make_image(fmt="PNG", size=(200, 300)):
"""A real image in memory, so tests need no files on disk."""
buffer = BytesIO()
Image.new("RGB", size, (12, 75, 51)).save(buffer, fmt)
return buffer.getvalue()
MEDIA_FOR_TESTS = tempfile.mkdtemp()
@override_settings(MEDIA_ROOT=MEDIA_FOR_TESTS) # never write into the real media folder
class CoverUploadTests(BookShelfTestCase):
@classmethod
def tearDownClass(cls):
shutil.rmtree(MEDIA_FOR_TESTS, ignore_errors=True)
super().tearDownClass()
def upload(self, name, content, content_type):
cover = SimpleUploadedFile(name, content, content_type=content_type)
return self.client.post(f"/api/books/{self.swami.id}/cover/", {"cover": cover}, format="multipart")
def test_staff_can_upload_a_png_cover(self):
self.client.force_authenticate(self.priya)
response = self.upload("swami.png", make_image(), "image/png")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertRegex(response.data["cover"], r"/media/covers/[0-9a-f]{32}\.png$")
def test_text_file_with_image_name_is_rejected(self):
self.client.force_authenticate(self.priya)
response = self.upload("swami.jpg", b"not really a picture", "image/jpeg")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)The full class also checks that a GIF gets "Use a JPEG, PNG or WebP image." and that Kabir's upload gets 403.
Step 4: run them, then make them fast
python manage.py testFound 15 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). ............... ---------------------------------------------------------------------- Ran 15 tests in 56.971s OK Destroying test database for alias 'default'...
Each dot is a passing test. But 57 seconds for 15 tests is slow, and slow tests stop being run. The cause is password hashing: Django's default hasher is deliberately slow to protect real passwords, and every create_user and login pays that price. Tests do not need strong hashing. Create config/test_settings.py:
from config.settings import * # noqa: F403
# Tests only: a fast (and weak) hasher. Never use it for real passwords.
PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]python manage.py test --settings=config.test_settingsRan 15 tests in 3.070s
From 57 seconds to 3. Production settings never import this file.
Step 5: the same tests with pytest-django
Many teams prefer pytest: plain assert, fixtures and short test functions. pytest-django lets pytest run Django tests, including the APITestCase classes you already have. Install it and add backend/pytest.ini:
python -m pip install pytest-django
python -m pip freeze > requirements.txt[pytest]
DJANGO_SETTINGS_MODULE = config.test_settings
python_files = tests.py test_*.pyNow new tests can be plain functions. Create books/test_reading_time.py:
import pytest
from rest_framework.test import APIClient
@pytest.fixture
def api():
return APIClient()
@pytest.mark.parametrize(
("body", "days"),
[
({"pages": 320, "pages_per_day": 25}, 13),
({"pages": 210}, 11), # pages_per_day defaults to 20
({"pages": 1, "pages_per_day": 500}, 1),
],
)
def test_reading_time(api, body, days):
response = api.post("/api/reading-time/", body, format="json")
assert response.status_code == 200
assert response.data["days"] == days
@pytest.mark.django_db
def test_empty_shelf_lists_no_books(api):
assert api.get("/api/books/").json() == []A fixture (api) is a value pytest creates and passes to any test that names it. parametrize runs one test with several inputs. pytest-django blocks database access unless a test asks for it with @pytest.mark.django_db; the reading-time calculator does not touch the database, so it does not need the mark. Run everything:
python -m pytestplatform win32 -- Python 3.14.8, pytest-9.2.0, pluggy-1.7.0 django: version: 6.1.3, settings: config.test_settings (from ini) configfile: pytest.ini plugins: django-4.14.0 collected 19 items accounts\tests.py .... [ 21%] books\test_reading_time.py . [ 26%] books\tests.py ........... [ 84%] books\test_reading_time.py ... [100%] ============================= 19 passed in 3.93s ==============================
(The first and rootdir lines are left out.) pytest-django runs database tests before the others, which is why test_reading_time.py appears twice: one dot for the database test, then three for the calculator.
Now see a test catch a bug. We changed one line in books/permissions.py to return True # BUG: forgot the owner check and ran only the matching test with -k edit:
================================== FAILURES ===================================
_________ ReviewApiTests.test_reader_cannot_edit_someone_elses_review _________
def test_reader_cannot_edit_someone_elses_review(self):
self.client.force_authenticate(self.kabir)
response = self.client.patch(f"/api/reviews/{self.priya_review.id}/", {"rating": 1})
> self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
E AssertionError: 200 != 403
books\tests.py:68: AssertionError
=========================== short test summary info ===========================
FAILED books/tests.py::ReviewApiTests::test_reader_cannot_edit_someone_elses_review
====================== 1 failed, 18 deselected in 6.99s =======================Kabir could change Priya's rating (200), and the test said so in one line. We restored the check and the suite passed again.
Step 6: set up Vitest for React
Vitest runs tests with Vite's own transforms, so JSX and imports work exactly as in the app. jsdom gives it a fake browser DOM inside Node. React Testing Library renders components and finds elements the way a user would: by role, label and text. From frontend:
npm install -D vitest jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom @testing-library/user-eventAdd a test block to vite.config.js, next to plugins, and "test": "vitest" to the scripts in package.json:
test: {
environment: "jsdom", // a fake browser DOM inside Node
setupFiles: ["./src/test/setup.js"],
},src/test/setup.js runs before every test file:
import "@testing-library/jest-dom/vitest"; // adds toBeInTheDocument() and friends
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";
afterEach(() => cleanup()); // unmount everything between testsTesting Library only cleans up by itself when the test runner has global afterEach. Vitest does not, unless you turn on globals, so we call cleanup() ourselves.
Step 7: component tests
Pure functions are the easiest start. src/utils/format.test.js checks formatRating(4.5, 2), the singular "1 review", null as "No ratings yet", and that formatDate("2026-11-15T20:00:00Z") is "16 Nov 2026" in Indian time.
BookCard contains a <Link>, so it needs a router around it. Without one, the test crashed with:
TypeError: Cannot destructure property 'basename' of 'React$1.useContext(...)' as it is null. ❯ LinkWithRef node_modules/react-router/dist/development/lib/dom/lib.js:288:8
MemoryRouter is a router that keeps its history in memory, perfect for tests. src/components/BookCard.test.jsx uses the saved API answer from src/mocks/books.json:
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { expect, test } from "vitest";
import books from "../mocks/books.json";
import BookCard from "./BookCard.jsx";
test("links the title to the book page", () => {
const swami = books.find((b) => b.title === "Swami and Friends");
render(
<MemoryRouter>
<BookCard book={swami} />
</MemoryRouter>,
);
expect(screen.getByRole("link", { name: "Swami and Friends" })).toHaveAttribute("href", `/books/${swami.id}`);
expect(screen.getByRole("img", { name: "4.5 out of 5 stars" })).toBeInTheDocument();
});The form test replaces the API client with fakes using vi.mock, so no server is needed, and drives the form with user-event, which types and clicks like a person. It provides the auth context directly instead of running AuthProvider:
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test, vi } from "vitest";
import { apiFetch } from "../api/client.js";
import { AuthContext } from "../auth/auth-context.js";
import ReviewForm from "./ReviewForm.jsx";
vi.mock("../api/client.js"); // every export becomes a fake function
test("shows Django's field and form errors where they belong", async () => {
const user = userEvent.setup();
const error = Object.assign(new Error("Request failed with status 400"), {
status: 400,
data: {
comment: ["Ensure this field has no more than 1000 characters."],
non_field_errors: ["The fields book, user must make a unique set."],
},
});
vi.mocked(apiFetch).mockRejectedValue(error);
render(
<AuthContext value={{ user: { id: 2, username: "kabir", is_staff: false }, refresh: vi.fn() }}>
<ReviewForm bookId="2" onSaved={vi.fn()} />
</AuthContext>,
);
await user.selectOptions(screen.getByLabelText("Rating"), "5");
await user.click(screen.getByRole("button", { name: "Post review" }));
expect(await screen.findByRole("alert")).toHaveTextContent("The fields book, user must make a unique set.");
expect(screen.getByText("Ensure this field has no more than 1000 characters.")).toBeInTheDocument();
expect(screen.getByLabelText("Comment (optional)")).toHaveAttribute("aria-invalid", "true");
});The error bodies are copied from real API answers in earlier lessons, so the test checks the real contract. Two more tests in the same file check that an empty rating sends no request and that a good review calls apiFetch("/reviews/", ...) with the exact JSON body. src/auth/RequireAuth.test.jsx renders the guard inside a MemoryRouter with initialEntries={["/account"]} and checks the three cases: checking, logged out (the login page appears), and logged in. Run them all once with npx vitest run --reporter=verbose (plain npm test stays running and re-tests on every save):
✓ src/utils/format.test.js > formatRating > shows one decimal and the review count
✓ src/utils/format.test.js > formatRating > uses the singular for one review
✓ src/utils/format.test.js > formatRating > treats null as no ratings, not zero
✓ src/utils/format.test.js > formatDate shows Indian time, even for a UTC timestamp
✓ src/auth/RequireAuth.test.jsx > sends a logged-out visitor to the login page
✓ src/auth/RequireAuth.test.jsx > waits while the login check is running
✓ src/auth/RequireAuth.test.jsx > shows the page to a logged-in user
✓ src/components/BookCard.test.jsx > links the title to the book page
✓ src/components/BookCard.test.jsx > shows 'No ratings yet' and no stars for an unrated book
✓ src/components/ReviewForm.test.jsx > asks for a rating before sending anything
✓ src/components/ReviewForm.test.jsx > posts the review as JSON and reports success
✓ src/components/ReviewForm.test.jsx > shows Django's field and form errors where they belong
Test Files 4 passed (4)
Tests 12 passed (12)A test is just code that checks
There is no magic inside a test runner. This example renders a small card into a detached element, checks the text, and prints the results, which is roughly what Testing Library and Vitest do for you with nicer messages:
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
function formatRating(average, count) {
if (average === null) return "No ratings yet";
return `${average.toFixed(1)} from ${count} ${count === 1 ? "review" : "reviews"}`;
}
function BookCard({ book }) {
return (
<article>
<h2>{book.title}</h2>
<p>{formatRating(book.average_rating, book.review_count)}</p>
</article>
);
}
function check(name, book, expected) {
const box = document.createElement("div");
const root = createRoot(box);
flushSync(() => root.render(<BookCard book={book} />)); // render now, not later
const text = box.querySelector("p").textContent;
root.unmount();
return { name, pass: text === expected, text };
}
const results = [
check("rated book", { title: "Godaan", average_rating: 5, review_count: 1 }, "5.0 from 1 review"),
check("unrated book", { title: "Malgudi Days", average_rating: null, review_count: 0 }, "No ratings yet"),
check("plural", { title: "Swami and Friends", average_rating: 4.5, review_count: 2 }, "4.5 from 2 review"),
];
createRoot(document.getElementById("root")).render(
<ul>
{results.map((r) => (
<li key={r.name} style={{ color: r.pass ? "green" : "#b00020" }}>
{r.pass ? "PASS" : "FAIL"} {r.name}: got "{r.text}"
</li>
))}
</ul>
);The third check fails on purpose: it expects "review" where the code correctly says "reviews". Fix the expected text and run it again. When a test fails, first ask whether the code or the test is wrong.
Common mistakes
- Testing only the happy path. Most API bugs are missing checks. Test what must be refused.
- Trusting the test client's CSRF. It skips CSRF unless you use
enforce_csrf_checks=True. - Writing test uploads into
media/. OverrideMEDIA_ROOTwith a temporary folder. - Forgetting the cache. Throttle counts survive between tests; clear the cache in
setUp. - Rendering router components without a router. Wrap them in
MemoryRouter.
Interview questions
1. What is the difference between force_authenticate and logging in during a test?
force_authenticate sets the request user directly and skips authentication and CSRF, which suits permission tests. A real login test posts credentials with a CSRF token through a client that enforces CSRF, so it proves the whole login flow works.
2. Why do Django tests get faster with a different password hasher?
The default PBKDF2 hasher runs many iterations on purpose, to slow down attackers. Tests create users and log in often, so they pay that cost repeatedly. A test-only settings file can use a fast hasher, because test passwords protect nothing.
3. What does @pytest.mark.django_db do?
pytest-django blocks database access by default so tests stay fast and explicit. The mark allows the test to use the database, wrapped in a transaction that is rolled back afterwards.
4. Why mock apiFetch in React component tests?
Component tests should check how the component behaves for each API answer, without a running Django server. Mocking the client lets the test return success, field errors or a 403 instantly and check what the user sees. The API's own tests prove the server side.
Key points
- Put the most tests on the API: permissions, validation, the CSRF login and uploads.
APITestCasegives a rolled-back database and anAPIClient; useforce_authenticatefor permission tests.- Use
APIClient(enforce_csrf_checks=True)andcache.clear()for real login and throttle tests. - A test settings file with a fast password hasher cut our run from 57 seconds to 3.
- pytest-django runs the same tests plus plain functions, fixtures and
parametrize. - Vitest + jsdom + Testing Library test components; wrap router components in
MemoryRouterand mockapiFetch.
Exercise
Add two tests. In Django: staff can remove a cover with DELETE /api/books/<id>/cover/, which returns 204, and the book's cover becomes null afterwards. In Vitest: a splitErrors test checking that {status: 400, data: {book: ["Invalid pk \"99\" - object does not exist."]}} with field names ["rating", "comment"] puts the message in the form list.
Show solution
# books/tests.py, inside CoverUploadTests
def test_staff_can_remove_a_cover(self):
self.client.force_authenticate(self.priya)
self.upload("swami.png", make_image(), "image/png")
response = self.client.delete(f"/api/books/{self.swami.id}/cover/")
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.assertIsNone(self.client.get(f"/api/books/{self.swami.id}/").data["cover"])// src/utils/errors.test.js
import { expect, test } from "vitest";
import { splitErrors } from "./errors.js";
test("errors for fields the form does not show go to the form list", () => {
const error = { status: 400, data: { book: ['Invalid pk "99" - object does not exist.'] } };
expect(splitErrors(error, ["rating", "comment"])).toEqual({
fields: {},
form: ['Invalid pk "99" - object does not exist.'],
});
});Both tests use only what earlier steps built: the upload() helper and the temporary MEDIA_ROOT keep the Django test away from real files, and the Vitest test needs no DOM at all, because splitErrors is a pure function.
Quick Quiz
1. Which client setting makes a DRF test check CSRF like a browser?
Test clients skip CSRF unless you ask them to enforce it.
2. Why did BookShelf's tests drop from 57 seconds to 3?
Password hashing is slow on purpose; tests do not need that protection.
3. A component that renders <Link> crashes in a test. What is missing?
Link reads the router's context, which only exists inside a router.
4. Where should most BookShelf tests that protect security rules live?
Only the API enforces rules; React tests cannot prove a request is refused.
Learn Django + React with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
