Reputation: 25072
I'm using NestJS Queues via Bull and writing unit tests in Jest. I want to skip the processing of jobs triggered during testing.
There's a GH issue on test mode for Bull but they won't implement it.
Preferably I'd avoid extensive mocking, a simple option on BullModule
would be best.
Upvotes: 4
Views: 4696
Reputation: 141
I also had a hard time with this, so I'm posting my solution. I'm just simplifying my code for this purpose, so use with caution, there might be some typos etc.
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});
});
});
I don't recommend unit tests having side effects - like storing data in the DB or redis, that's why this approach. However if you prefer to actually store the jobs in redis, you might find some inspiration here: https://github.com/nestjs/bull/blob/master/e2e/module.e2e-spec.ts
Upvotes: 7
Reputation: 25072
Currently, my workaround is to delay test jobs by an arbitrary high timeframe. I can Initialize BullModule
when building my test module as follows:
moduleRef = await Test.createTestingModule({
moduleRef = await Test.createTestingModule({
imports: [
BullModule.forRoot({
redis: process.env.REDIS_URL,
defaultJobOptions: {
delay: 99999999999999999,
},
}),
// ...,
],
}).compile();
I don't like this so much as the jobs will idle in Redis.
Upvotes: 0