How do I test a CRUD API?
Use Jest and supertest. Test happy paths (create, read, update, delete) and error paths (validation, not found, not authorized, duplicate). Use a test database and clean between tests. Run tests in CI.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in The Thought Process for Writing a CRUD API
Identify the resource, define the schema, list the endpoints, write validation schemas, write controller functions, write the router, mount it, handle edge cases (not found, not authorized, duplicate), test, and document. Repeat for each resource.
GET /resource (list), POST /resource (create), GET /resource/:id (read), PATCH /resource/:id (update), DELETE /resource/:id (delete). Use plural nouns for the path. Version with /api/v1.
Not found: throw new ApiError(404, 'Resource not found'). Not authorized: compare the resource's owner to req.user.userId; throw 403 if they do not match. Validation: the validate middleware handles it. Duplicate: catch the 11000 error and return 409.
Still have questions?
Browse all our FAQs or reach out to our support team
