首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NestJS Mock RabbitMQ in Jest

NestJS Mock RabbitMQ in Jest
EN

Stack Overflow用户
提问于 2022-07-24 09:11:03
回答 1查看 391关注 0票数 1

我有一个AppModule文件如下:

代码语言:javascript
运行
复制
import { Module } from '@nestjs/common'
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq'

@Module({
    imports: [
        RabbitMQModule.forRoot(RabbitMQModule, {
            exchanges: [
                {
                    name: 'my_rabbit',
                    type: 'direct',
                },
            ],
            uri: process.env.RABBITMQ_URI,
            connectionInitOptions: { wait: true },
        }),
    ],
})
export class AppModule {}

我尝试过像这样使用@golevelup/nestjs-rabbitmq来模拟rabbitmq:

代码语言:javascript
运行
复制
import { Module } from '@nestjs/common'
import { RabbitMQModule } from '@golevelup/nestjs-rabbitmq'

beforeEach(async () => {
        const module: TestingModule = await Test.createTestingModule({
            imports: [
                AppModule
            ],
        })
            .overrideProvider(AmqpConnection)
            .useValue(createMock<AmqpConnection>())
            .compile()
    })

这让我犯了错误:

代码语言:javascript
运行
复制
[Nest] 2745  - 24/07/2022, 17:02:54   ERROR [AmqpConnection] Disconnected from RabbitMQ broker (default)
Error: connect ECONNREFUSED 127.0.0.1:5672

如果我嘲笑整个rabbitmq模块,比如:

代码语言:javascript
运行
复制
jest.mock('@golevelup/nestjs-rabbitmq')

我会犯这样的错误:

代码语言:javascript
运行
复制
Nest cannot create the AppModule instance.
    The module at index [0] of the AppModule "imports" array is undefined.

有人成功地模仿过RabbitMQ吗?如果可能的话请协助。

EN

回答 1

Stack Overflow用户

发布于 2022-08-23 16:24:18

我解决了这样模拟AmqpConnection的问题。

代码语言:javascript
运行
复制
    import { AmqpConnection } from "@nestjs-plus/rabbitmq";
    import { TestingModule, Test } from "@nestjs/testing";
    import { IntegrationQueueService } from "./integration-queue.service";

    describe('IntegrationQueueService', () => {

      type MockType<T> = {
         [P in keyof T]?: jest.Mock<{}>;
      };
  

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

 
      let service: IntegrationQueueService;

      beforeEach(async () => {
         const module: TestingModule = await Test.createTestingModule({
            providers: [
                IntegrationQueueService,
                {
                    provide: AmqpConnection,
                    useFactory: mockFactory,
                },
            ],

         })
            .compile();

        service = module.get<IntegrationQueueService> (IntegrationQueueService);
    });


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

})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73097067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档