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

NestJS中Jest模拟AmqpConnection失败,仍调用真实RabbitMQ

NestJS测试中模拟AmqpConnection仍调用真实RabbitMQ的问题

开发一个与RabbitMQ交互的NestJS应用,编写API测试用例时尝试模拟AmqpConnection,但测试仍在调用真实的RabbitMQ。作为Jest测试新手,想排查是否遗漏关键步骤。

代码示例

MyControllerSpec.ts

describe('MyController', () => {
    let app
    let module: TestingModule
    

    beforeEach(async () => {
        jest.clearAllMocks()

        module = await Test.createTestingModule({
            controllers: [MyController],
            imports: [AppModule],
            providers: [
                {
                    provide: AmqpConnection,
                    useClass: MockAmqpConnection
                }
            ]
        }).compile()

        app = module.createNestApplication()
        await app.init()
    }, 10000)

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

    it('should be defined', () => {
        const controller = module.get<MyController>(
            MyController
        )
        expect(controller).toBeDefined()
    })

    it('should call MyService.get with queryParams', async () => {
        //code
    })
})

MockAmqpConnection.ts

class MockAmqpConnection {
    private _connected: boolean = true
    get connected(): boolean {
        return true
    }
    async connect(): Promise<void> {
        this._connected = true
    }
    async disconnect(): Promise<void> {
        this._connected = false
    }
}

export { MockAmqpConnection }

报错信息

Please migrate your code to use AWS SDK for JavaScript (v3).
For more information, check the migration guide at https://a.co/7PzMCcy
(Use `node --trace-warnings ...` to show where the warning was created)
[Nest] 32466  - 05/09/2024, 10:27:07 AM   ERROR [AmqpConnection] Disconnected from RabbitMQ broker (default)
Error: getaddrinfo ENOTFOUND <actual rabitmq url>

Error: Failed to connect to a RabbitMQ broker within a timeout of 5000ms

    at workspace-nestjs/n1ab/node_modules/@golevelup/nestjs-rabbitmq/src/amqp/connection.ts:192:17

已尝试的解决方案

  • 查找参考了NestJS模拟RabbitMQ的相关测试方案
  • 使用jest.mock模拟RabbitmqHealthIndicator:
jest.mock('../../service/rabbitmq.health.indicator', () => {
return {
RabbitmqHealthIndicator: jest.fn().mockImplementation(() => ({
isHealthy: jest.fn().mockResolvedValue({ status: 'up' })
}))
})
  • 使用MockType创建模拟工厂:
type MockType<T> = {
[P in keyof T]?: jest.Mock<{}>
}

const mockFactory: () => MockType<AmqpConnection> = jest.fn(() => ({
publish: jest.fn(() => AmqpConnection)
}))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:40:10