问题描述
我正在使用supertest测试AuthenticationController
。为此,我使用与主文件main.ts
中使用的配置相同的配置来模拟我的应用程序:
// authentication.controller.ts
describe("The AuthenticationController",() => {
let app: InestApplication;
beforeEach(async () => {
userData = {
...mockedUser,};
const userRepository = {
create: jest.fn().mockResolvedValue(userData),save: jest.fn().mockReturnValue(Promise.resolve()),};
const module = await Test.createTestingModule({
controllers: [...],providers: [...],}).compile();
app = module.createnestApplication();
app.useGlobalPipes(new ValidationPipe());
app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
await app.init();
});
});
这通常可以正常工作,但是每当我测试一个不应该返回密码或ID的控制器时(由于实体定义中使用@Exclude()
装饰器,测试仍会将其返回给我。) >
在Postman上手动测试端点仍然可以正常工作。
有人知道什么可能导致该问题吗?
解决方法
我刚刚从NestJS的一名开发人员的官方Discord上得到了一个答案:https://discord.com/invite/nestjs
原来,该错误来自以下事实:在我的userRepository中模拟create
的返回值时,我实际上是在返回对象而不是类的实例。因此,必须替换以下几行:
const userRepository = {
create: jest.fn().mockResolvedValue(userData),save: jest.fn().mockReturnValue(Promise.resolve()),};
通过以下方式:
const userRepository = {
create: jest.fn().mockResolvedValue(new User(userData)),};
只需返回一个对象,就不会考虑装饰器,因此必须返回一个类实例。