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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With