NestJS Bull Queues:如何跳过测试环境中的处理?

问题描述

我正在使用 NestJS Queues via Bull 并在 Jest 中编写单元测试。我想跳过测试期间触发的作业的处理。

test mode for Bull 上存在 GH 问题,但他们不会实施。

我最好避免大量的模拟,最好在 if 上使用简单的选项。

解决方法

目前,我的解决方法是将测试作业延迟任意高的时间范围。我可以在构建我的测试模块时初始化 BullModule,如下所示:

moduleRef = await Test.createTestingModule({
moduleRef = await Test.createTestingModule({
  imports: [
    BullModule.forRoot({
      redis: process.env.REDIS_URL,defaultJobOptions: {
        delay: 99999999999999999,},}),// ...,],}).compile();

我不太喜欢这样,因为作业会在 Redis 中闲置。

,

我也遇到了困难,所以我发布了我的解决方案。我只是为了这个目的简化我的代码,所以请谨慎使用,可能会有一些拼写错误等。

describe('JobCreatorService',() => {
  let service: JobCreatorService;
  let moduleRef: TestingModule;

  const exampleQueueMock = { add: jest.fn() };

  beforeEach(async () => {
    jest.resetAllMocks();
    moduleRef = await Test.createTestingModule({
      imports: [
        BullModule.registerQueue({
          name: EXAMPLE_QUEUE,})
      .overrideProvider(getQueueToken(EXAMPLE_QUEUE))
      .useValue(exampleQueueMock)
      .compile();

    service = moduleRef.get<JobCreatorService>(JobCreatorService);
  });

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

  it('should dispatch job',async () => {
    await service.methodThatDispatches();
    expect(exampleQueueMock.add).toHaveBeenCalledWith({example: jobData});
  });
});

我不推荐有副作用的单元测试——比如将数据存储在 DB 或 redis 中,这就是这种方法的原因。但是,如果您更喜欢将作业实际存储在 redis 中,您可能会在这里找到一些灵感:https://github.com/nestjs/bull/blob/master/e2e/module.e2e-spec.ts