简体   繁体   English

Mocking NestJS 中的公牛队列

[英]Mocking Bull queues in NestJS

I am trying to test that after sending a request to one of my controllers, the queue pushes a job.我正在尝试测试在向我的一个控制器发送请求后,队列会推送作业。 Implementation itself works as expected.实现本身按预期工作。

This is my app.module.ts这是我的app.module.ts

    @Module({
    imports: [
    HttpModule,
    TypeOrmModule.forRoot(typeOrmConfig),
    BullModule.forRoot({
      redis: {
        host: redisConfig.host,
        port: redisConfig.port,
      },
    }),
    // Bunch of unrelated modules
     ],
     providers: [
    {
      provide: APP_FILTER,
      useClass: AllExceptionsFilter,
    },
    ],
     controllers: [SomeControllers],
    })
    export class AppModule {}

And this is how my import.module.ts (module using queues) looks like:这就是我的import.module.ts (使用队列的模块)的样子:

@Module({
  imports: [
    BullModule.registerQueue({
      name: importQueueName.value,
    }),
   //More unrelated modules,
  ],
  providers: [
    //More services, and bull consumer and producer,
    ImportDataProducer,
    ImportDataConsumer,
    ImportDataService,
  ],
  controllers: [ImportDataController],
})
export class ImportDataModule {}

So as I said functionally the implementation works good所以正如我所说,在功能上实现效果很好

I tried to follow this approach我试图遵循这种方法

Which does not register the queue in the beforeAll hook, and I'm getting哪个没有在 beforeAll 钩子中注册队列,我得到了

 Driver not Connected

And this approach这种做法

Which registers a queue in the beforeAll hook in the test suite, and I am getting:在测试套件的 beforeAll 挂钩中注册了一个队列,我得到:

 TypeError: Cannot read properties of undefined (reading 'call')

      at BullExplorer.handleProcessor (node_modules/@nestjs/bull/dist/bull.explorer.js:95:23)
      at MapIterator.iteratee (node_modules/@nestjs/bull/dist/bull.explorer.js:59:26)
      at MapIterator.next (node_modules/iterare/src/map.ts:9:39)
      at FilterIterator.next (node_modules/iterare/src/filter.ts:11:34)
      at IteratorWithOperators.next (node_modules/iterare/src/iterate.ts:19:28)
          at Function.from (<anonymous>)
      at IteratorWithOperators.toArray (node_modules/iterare/src/iterate.ts:227:22)
      at MetadataScanner.scanFromPrototype (node_modules/@nestjs/core/metadata-scanner.js:12:14)
      at node_modules/@nestjs/bull/dist/bull.explorer.js:56:34
          at Array.forEach (<anonymous>)

This is my 'base test suite':这是我的“基本测试套件”:

describe('Queue test suite', () => {
  let app: INestApplication;
  const importQueue: any = { add: jest.fn() };
  beforeAll(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule, ImportDataModule],
    })
      .overrideProvider(importQueueName.value)
      .useValue(importQueue)
      .compile();

    app = moduleFixture.createNestApplication();
    app.useGlobalPipes(
      new ValidationPipe({
        transform: true,
        whitelist: true,
        forbidNonWhitelisted: true,
      }),
    );
    await app.init();
  });

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

  test('A job should be pushed', async () => {
    await request(app.getHttpServer())
      .post('/some/route')
      .attach('file', __dirname + '/some.file')
      .expect(HttpStatus.CREATED);
   

    expect(importQueue.add).toHaveBeenCalled();
  });
});

Any idea on what could be wrong here?关于这里可能有什么问题的任何想法? Thanks!谢谢!

I had the same issue, the problem is with your mockQueue .我有同样的问题,问题出在你的mockQueue You need to add a process mocked function.您需要添加一个模拟 function 的process

This should work for you!这应该适合你!

const importQueue: any = { 
  add: jest.fn(),
  process: jest.fn(),
};

And this is how I tested it.这就是我测试它的方式。

expect(mockQueue.add).toBeCalledTimes(1);
      expect(mockQueue.add).nthCalledWith(
        1,
        PendoJobNames.SCR,
        {
          ...mockJobDto,
        },
        {
          jobId: mockDto.visitorId,
          removeOnComplete: true,
          removeOnFail: true,
        },
      );
    ```

The answer by @moogs is correct, but I had to add another function as well. @moogs 的答案是正确的,但我还必须添加另一个 function。

const queueMock = {
  add: jest.fn(),
  process: jest.fn(),
  on: jest.fn()
};

The on function, and it worked. on function 上,它起作用了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM