“类型错误:无法读取未定义的属性‘关闭’”在 E2E 测试中

时间:2021-02-13 19:19:48

标签: typescript websocket jestjs nestjs

我想测试我的 WebSocket,但我遇到的问题是我的测试出错并且测试过程一直在运行并且没有结束。 (错误见图片)。

enter image description here

已经导致错误的代码:

describe("Event Gateway (E2E)", () => {
    let app: INestApplication;

    beforeAll(async () => {
        app = await globalBeforeAll([GatewayModule]);
    });

    afterAll(async () => {
        await app.close();
    });

    describe("Connection to WebSocket", () => {
        it("should be successfully", () => {
            // here should come some expectations ...
        });
    });
});

globalBeforeAll 只是一个帮助方法,使测试更具可读性。这包含了守卫的覆盖以及另外的 useWebSocketAdapter(new RedisIoAdapter(application))

RedisIoAdapter 稍后将成为它自己的适配器,然后我可以使用它通过 Redis 制作 PubSub。出于测试目的,它目前看起来非常基本,如下所示:

import { ServerOptions } from "socket.io";
import { IoAdapter } from "@nestjs/platform-socket.io";

export class RedisIoAdapter extends IoAdapter {
    createIOServer(port: number, options?: ServerOptions): any {
        return super.createIOServer(port, options);
    }
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题确实出在 globalBeforeAll 中。以前,该方法如下所示:

export async function globalBeforeAll(additionalModules: Array<{ new (): any }>): Promise<INestApplication> {
    const app = await Test.createTestingModule(ModuleMetadataBuilder.build(additionalModules, true))
        .overrideGuard(JwtAuthGuard)
        .useClass(OverridesAuthGuard)
        .overrideGuard(RolesAuthGuard)
        .useClass(OverridesRolesGuard)
        .compile()
        .then((application) => application
            .createNestApplication()
            .useWebSocketAdapter(new RedisIoAdapter(app))
            .init(),
        );

    app.enableShutdownHooks();
    Authorizer.init(app);

    return app;
}

我不得不按如下方式更改它,现在它可以工作了:

export async function globalBeforeAll(additionalModules: Array<{ new (): any }>): Promise<INestApplication> {
    const app = await Test.createTestingModule(ModuleMetadataBuilder.build(additionalModules, true))
        .overrideGuard(JwtAuthGuard)
        .useClass(OverridesAuthGuard)
        .overrideGuard(RolesAuthGuard)
        .useClass(OverridesRolesGuard)
        .compile()
        .then((application) => application.createNestApplication());

    app.useWebSocketAdapter(new RedisIoAdapter(app));
    app.enableShutdownHooks();
    Authorizer.init(app);

    return app.init();
}