NestJS:Supertest e2e测试跳过序列化程序拦截器

问题描述

我正在使用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)),};

只需返回一个对象,就不会考虑装饰器,因此必须返回一个类实例。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...