NestJS,SuperTest - 套接字没有得到事件

NestJS, SuperTest - Socket doesn't get event

我正在努力进行关于我的套接字的端到端测试。

套接字连接并很好地记录到 NestJS 网关,但它没有进入我的侦听器 bedRequest

我的测试包括通过 supertest 发送一个创建请求,最后,网关向连接的套接字广播一条消息,我想验证它。

在网关日志中,我看到客户端已连接、登录和断开连接(如果有帮助的话)。

提前致谢。

 it("/POST bedRequest", (done) => {
        let bedRequestCreate = some payload
        let expectedResult = other payload

        const address = app.getHttpServer().listen().address();
        const baseAddress = `http://[${address.address}]:${address.port}`;
        const client = io(`${baseAddress}/`);

        client.on("connect", () => { // this works
            client.emit("logIn", {access_token: accessToken}, (isConnected) => {
                expect(isConnected).toBeTruthy(); // this works

                client.on("bedRequest", (data) => { // this doesn't work
                    expect(JSON.parse(data)).toMatchObject({
                        siteId: bedRequestCreate.siteId,
                        ...expectedResult
                    });
                    done();
                });
            });
        });

        return request(app.getHttpServer())
            .post("/api/bedRequest/")
            .send(bedRequestCreate)
            .set('Accept', 'application/json')
            .set('Authorization', 'Bearer ' + accessToken)
            .expect('Content-Type', /json/)
            .expect(201)
            .end((err, res) => {
                if (err) return done(err);
                expect(res.body.generatedMaps[0]).toMatchObject(expectedResult); // this works
            });
    });

网关:

@WebSocketGateway()
export class SocketGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {

    @WebSocketServer() server: Server;

    wsClients = [];

    private logger: Logger = new Logger('SocketGateway');

    handleDisconnect(client: Client) {
        for (let i = 0; i < this.wsClients.length; i++) {
            if (this.wsClients[i] === client) {
                this.wsClients.splice(i, 1);
                break;
            }
        }
        this.logger.log(`Client disconnected: ${client.id}`);
    }

    broadcast(event: String, message: any) {
        const broadCastMessage = JSON.stringify(message);
        for (let c of this.wsClients) { // sends to the right client
            c.send(event, broadCastMessage);
        }
    }

    @UseGuards(WebSocketJwtAuthGuard)
    @SubscribeMessage("logIn")
    handleLogIn(client) { // works
        this.logger.log(`Socket Client connected : ${client.id} for user ${client.user.id} / ${client.mail}`);
        this.wsClients.push(client);
        return true;
    }

    handleConnection(client) {
        return `Client connected: ${client.id}`;
    }

    afterInit() {
        this.logger.log("SocketGateway initialized")
    }

}

好的,我找到了...

这是因为这一行:c.send(event, broadCastMessage);

我将 send 更改为 emit,它工作正常。