You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS中Jest如何Mock作为参数的Socket方法并断言调用

如何在NestJS的Jest测试中Mock并断言WebSocket的compress和disconnect方法调用

要验证socket.compress(true)和socket.disconnect(true)的调用,核心是保存Jest mock函数的引用,这样就能在调用handleConnection后对这些mock函数做断言。以下是修改后的完整测试代码:

import { Test, TestingModule } from '@nestjs/testing';
import { DefaultGateway } from './default.gateway';
import { Sockt } from '../data.module';

describe('DefaultGateway', () => {
  let gateway: DefaultGateway;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [DefaultGateway],
    }).compile();

    gateway = module.get<DefaultGateway>(DefaultGateway);
  });

  it('should be defined', () => {
    expect(gateway).toBeDefined();
  });

  it('should call compress(true) when valid jwt is provided', () => {
    // 定义mock函数并保存引用
    const mockCompress = jest.fn();
    const mockDisconnect = jest.fn();

    const mockSocket = {
      compress: mockCompress,
      disconnect: mockDisconnect,
      handshake: { query: { jwt: '12sdf908' } },
    } as unknown as Sockt;

    gateway.handleConnection(mockSocket);

    // 断言compress被调用且参数为true
    expect(mockCompress).toHaveBeenCalledWith(true);
    // 断言disconnect没有被调用
    expect(mockDisconnect).not.toHaveBeenCalled();
  });

  it('should call disconnect(true) when no valid credentials are provided', () => {
    const mockCompress = jest.fn();
    const mockDisconnect = jest.fn();

    const mockSocket = {
      compress: mockCompress,
      disconnect: mockDisconnect,
      handshake: { query: {} }, // 无任何有效凭证
    } as unknown as Sockt;

    gateway.handleConnection(mockSocket);

    // 断言disconnect被调用且参数为true
    expect(mockDisconnect).toHaveBeenCalledWith(true);
    // 断言compress没有被调用
    expect(mockCompress).not.toHaveBeenCalled();
  });

  it('should call compress(true) when valid uuid and password are provided', () => {
    const mockCompress = jest.fn();
    const mockDisconnect = jest.fn();

    const mockSocket = {
      compress: mockCompress,
      disconnect: mockDisconnect,
      handshake: { query: { uuid: 'test-uuid', password: 'test-pass' } },
    } as unknown as Sockt;

    gateway.handleConnection(mockSocket);

    expect(mockCompress).toHaveBeenCalledWith(true);
    expect(mockDisconnect).not.toHaveBeenCalled();
  });
});

关键说明:

  • 每个测试用例单独定义mockCompress和mockDisconnect,避免测试用例之间的状态污染
  • 将mock函数传入mockSocket对象,确保handleConnection内部调用的是这些mock函数
  • 调用gateway.handleConnection(mockSocket)后,直接通过保存的mock函数引用做断言,验证调用参数和调用状态

内容的提问来源于stack exchange,提问作者Felipe Briga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 20:25:10