【问题标题】:NestJS: Supertest e2e tests skip serializer interceptorsNestJS:Supertest e2e 测试跳过序列化程序拦截器
【发布时间】:2020-10-28 17:46:04
【问题描述】:

我正在使用 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 上手动测试端点仍然可以正常工作。

有谁知道是什么导致了这个问题?

【问题讨论】:

    标签: javascript typescript nestjs supertest


    【解决方案1】:

    我刚刚从 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)),
        save: jest.fn().mockReturnValue(Promise.resolve()),
    };
    

    通过简单地返回一个对象,没有考虑装饰器,因此必须返回一个类实例。

    【讨论】:

    • 我一直在关注与您相同的教程,感谢您在此处发布此内容。我也对创建 TypeORM 实体的类实例感到困惑,但我通过在类上创建构造函数来解决这个问题。我不知道这是否是正确的解决方案,但至少它有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多