express-mocks-testing
Unit testing pattern for Express 5 controllers using node-mocks-http and @prisma/client mocks. Trigger: When writing unit tests for backend controllers, testing Express routes, or avoiding Supertest/Server instantiation.
- License 许可
- Apache-2.0
- 最近更新
- 2026-11-11
- Stars
- ★ 3
- Forks
- 0
01 前言 Front Matter
- name
- express-mocks-testing
- license
- Apache-2.0
- metadata
- { "author": "gentleman-programming", "version": "1.0" }
- description
- Unit testing pattern for Express 5 controllers using node-mocks-http and @prisma/client mocks. Trigger: When writing unit tests for backend controllers, testing Express routes, or avoiding Supertest/Server instantiation.
02 资源文件 2
- 参考文档templates/raw-finding.md467 B
- 参考文档templates/theme-readme.md172 B
03 SKILL.md 正文
When to Use
- When unit testing Express 5 controllers in isolation without starting the server.
- When you want to completely decouple from a real database.
- When testing specific logic, role filters, or validation branches inside a controller.
- Do NOT use this for End-to-End (E2E) integration tests that genuinely require testing the full middleware chain (CORS, body-parser, global error handlers). For E2E, use Supertest.
Critical Patterns
- NEVER instantiate the full Server: Do not import or instantiate
new Server()orappfromserver.ts. It causes slow tests and port conflicts. - Global Prisma Mock: Always use
jest.mock("@prisma/client", () => { ... })to intercept Prisma Client instantiations before the controller executes. - Isolate Request/Response: Use
createRequestandcreateResponsefromnode-mocks-httpto simulate Express objects. - Call Controller Directly: Invoke the controller method directly (e.g.,
await controller.sendMessage(req, res)). - Clear Mocks: Always run
jest.clearAllMocks()in thebeforeEachhook. - Assertions: Use
res._getJSONData()to verify JSON responses andres.statusCodeto check HTTP statuses.
Code Examples
Basic Controller Test Setup
import { createRequest, createResponse } from "node-mocks-http";
import { MyController } from "../my.controller";
import { PrismaClient } from "@prisma/client";
// 1. MOCK PRISMA GLOBALLY
jest.mock("@prisma/client", () => {
const mPrismaClient = {
user: {
findUnique: jest.fn(),
create: jest.fn(),
},
};
return { PrismaClient: jest.fn(() => mPrismaClient) };
});
const prismaMock = new PrismaClient() as jest.Mocked<any>;
describe("MyController", () => {
let controller: MyController;
beforeAll(() => {
controller = new MyController();
});
beforeEach(() => {
jest.clearAllMocks();
});
describe("getUser", () => {
it("should return 200 and the user data", async () => {
// Arrange
const req = createRequest({
method: "GET",
url: "/api/users/1",
params: { id: "1" },
user: { id_persona: "admin-123" } // If testing protected routes
});
const res = createResponse();
prismaMock.user.findUnique.mockResolvedValue({ id: "1", name: "John" });
// Act
await controller.getUser(req, res);
// Assert
expect(res.statusCode).toBe(200);
expect(res._getJSONData().name).toBe("John");
expect(prismaMock.user.findUnique).toHaveBeenCalledWith({
where: { id: "1" }
});
});
});
});
Commands
# Run backend tests
pnpm test
# Run specific test file
pnpm jest path/to/your/controller.test.ts
04 同仓库更多 Skills
skill-sync
Synchronizes skill metadata to AGENTS.md Auto-invoke sections. Trigger: When syncing skill metadata to AGENTS.md.
skill-creator
Creates new AI agent skills following the Agent Skills spec. Trigger: When user asks to create a new skill, add agent instructions, or document patterns for AI.
skill-commit
Creates professional git commits following conventional-commits format. Trigger: When creating commits, after completing code changes, when user asks to commit.
project-info
General monorepo structure and component overview. Trigger: When AI needs project context or component locations.
frontend-context
Frontend architecture, patterns and conventions for the Next.js 15 app. Trigger: When working on frontend code, components, pages, or API integration.
backend-service
暂无简介