在进行 e2e 测试时,您可能想要模拟对 prisma 的调用,但使用 NestJS 模块来找到正确执行此操作的方法可能会很复杂
对于寻找合适示例的人来说,这里是一种使用 jest-mock-extend
的方法您需要设置
jest.config.*
并准备prisma mock
的文件
jest.config.ts
import type { Config } from "jest";
const config: Config = {
moduleFileExtensions: ["ts", "js"],
rootDir: "src",
testRegex: ".*\\.specs\\.ts$",
transform: {
"^.+\\.(t|j)s$": "ts-jest",
},
testEnvironment: "node",
};
export default config;
prisma-mock.ts(也可与自定义客户端一起使用)
import { mockDeep, DeepMockProxy } from "jest-mock-extended";
import { PrismaClient } from "@prisma/client";
// Mock PrismaClient type
type PrismaType = DeepMockProxy<PrismaClient >;
// Mock PrismaClient using your schema, allowing all method set in service to be called by e2e tests
export const PrismaMock: PrismaType = mockDeep<PrismaClient>();
用户.e2e.specs.ts
import { Test } from "@nestjs/testing";
import {
NestFastifyApplication,
FastifyAdapter,
} from "@nestjs/platform-fastify";
// Import mockReset for PrismaMock + PrismaMock client
import { mockReset } from "jest-mock-extended"
import { PrismaMock } from "../../../../jest/prisma-mock";
// Controller + Service to be mocked
import { UserController } from "../controllers/user.controller";
import { UserService } from "../services/user.service";
// Mock of UserService
class UserServiceMock extends UserService {
constructor() {
super(PrismaPostgresqlMock);
}
}
// Mock of UserController
class UserControllerMock extends UserController {
constructor() {
super(new UserServiceMock());
}
}
beforeEach(() => {
// remove every value set to mocked function between each test
mockReset(PrismaPostgresqlMock);
});
describe("Users", () => {
// Setup fastify app
let app: NestFastifyApplication;
beforeAll(async () => {
// Create the mockModule using mocked controller + service
const userModuleMock = await Test.createTestingModule({
// Use mocked controller
controllers: [UserControllerMock],
// Provider have to provided this way as the controller expect the initial value
providers: [
{
provide: UserService,
useValue: UserServiceMock,
},
],
}).compile();
app = userModuleMock.createNestApplication<NestFastifyApplication>(
new FastifyAdapter()
);
await app.init();
await app.getHttpAdapter().getInstance().ready();
});
it(`/GET users`, async () => {
// Call to mock the prisma call made in this test (return 500 if not mocked)
PrismaPostgresqlMock.users.findMany.mockResolvedValue([]);
// Call the route in the mocked module (from the mocked controller)
const result = await app.inject({
method: "GET",
url: "/users",
});
expect(result.statusCode).toEqual(200);
expect(result.json()).toEqual([]);
});
afterAll(async () => {
await app.close();
});
});
有了这个,您就有了为 NestJs 项目中的每个模块创建 e2e 测试的基础
如果您对此有任何疑问或可能的优化,请随时发表评论