在 Jest 测试中有条件地模拟@golevelup/nestjs-rabbitmq

问题描述 投票:0回答:1

我正在尝试为我的应用程序编写一个笑话测试。我的应用程序使用 @golevelup/nestjs-rabbitmq 来建立连接。作为测试套件的一部分,我有条件地创建了 RabbitMQWrapperModule。这是 RabbitMQWrapperModule

import { Module, DynamicModule } from '@nestjs/common'
import {
  RabbitMQModule,
  RabbitMQConfig,
  MessageHandlerErrorBehavior
} from '@golevelup/nestjs-rabbitmq'
import { ConfigModule, ConfigService } from '@nestjs/config'

@Module({})
export class RabbitMQWrapperModule {
  static register(): DynamicModule {
      return {
          module: RabbitMQWrapperModule,
          imports: [
              RabbitMQModule.forRootAsync(RabbitMQModule, {
                  imports: [ConfigModule],
                  useFactory: async (configService: ConfigService) => {
                      const env = configService.get('NODE_ENV')
                      if (env === 'test') {
                          return {} as RabbitMQConfig
                      } else {
                          return {
                              uri: `${configService.get(
                                  'messageBus.connection.protocol'
                              )}://${configService.get(
                                  'messageBus.connection.username'
                              )}:${configService.get(
                                  'messageBus.connection.password'
                              )}@${configService.get(
                                  'messageBus.connection.hostname'
                              )}:${configService.get('messageBus.connection.port')}`,
                              connectionManagerOptions: {
                                  heartbeatIntervalInSeconds: configService.get(
                                      'messageBus.connection.heartbeatInterval'
                                  )
                              },
                              channels: {
                                  'channel-1': {
                                      prefetchCount: 1,
                                      default: true
                                  }
                              },
                              defaultSubscribeErrorBehavior: MessageHandlerErrorBehavior.ACK
                          }
                      }
                  },
                  inject: [ConfigService]
              })
          ],
          exports: [RabbitMQModule]
      }
  }
}

我创建了一个 test-setup.ts 文件

jest.mock( '/存储库' ) 导出 const createTestModule = async (): Promise => { 常量存储库模拟= 与 jest.Mock 一样未知的存储库

  const module: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
      controllers: [Controller],
      providers: [
          <service1>,
          <service2>,
          {
              provide: JwtService,
              useValue: mockJwtService
          }
      ]
  })
      .overrideProvider(RabbitMQModule)
      .useValue(MockedRabbitMqConnectionModule)
      .overrideProvider(JwtService)
      .useValue({
          decode: () => Promise.resolve(fakeUser)
      })
      .compile()
  config().jwt.skipVerify = true

  return module
}

这是我的规格文件

让应用程序 让模块:TestingModule

    beforeAll(async () => {
        jest.clearAllMocks()
        module = await createTestModule()
        app = module.createNestApplication()
        config().jwt.skipVerify = true
        await app.init()
    })

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

    it('should call generateIdListService.get with queryParams', (done) => {
        const requestBodyMock: QueryParam = {
            requestId: '111'
        }


        request(app.getHttpServer())
            .get('<url>')
            .send(requestBodyMock)
            .then((response) => {
                expect(response.status).toBe(200)
            
                done()
            })
    })

    
    })
})

根据环境有条件导入RabbitMQModule。在 RabbitMQWrapperModule 中,我添加了一个条件检查,当环境设置为“test”时,返回一个空对象 ({}) 作为 RabbitMQ 配置。如果值为空对象 {},这意味着 rabbitmq 未初始化且未建立连接。但在这种情况下,它尝试连接并收到此错误

ERROR [AmqpConnection] Disconnected from RabbitMQ broker (default)
TypeError: Cannot read properties of undefined (reading 'heartbeat')
    at /Users/ac/workspace/project/node_modules/amqp-connection-manager/dist/cjs/AmqpConnectionManager.js:231:42

有人成功嘲笑过RabbitMQ吗?如果可以的话请帮忙。

jestjs rabbitmq nestjs
1个回答
0
投票

经过一番研究,我发现了这个问题。我的项目有两个用于 RabbitMQ 连接的模块。我将这两个 RabbitMQ 模块合并为一个。现在,模拟正在按预期工作。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.