我在用着通过 Bull 的 NestJS 队列 https://docs.nestjs.com/techniques/queues并用 Jest 编写单元测试。我想跳过测试期间触发的作业的处理。
存在 GH 问题Bull 的测试模式 https://github.com/OptimalBits/bull/issues/962但他们不会实施。
最好我会避免广泛的嘲笑,这是一个简单的选择BullModule
会是最好的。
我也遇到了困难,所以我发布了我的解决方案。我只是为此目的简化了我的代码,因此请谨慎使用,可能会有一些拼写错误等。
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});
});
});
我不建议进行具有副作用的单元测试 - 例如将数据存储在数据库或 redis 中,这就是这种方法的原因。但是,如果您更喜欢将作业实际存储在 Redis 中,您可能会在这里找到一些灵感:https://github.com/nestjs/bull/blob/master/e2e/module.e2e-spec.ts https://github.com/nestjs/bull/blob/master/e2e/module.e2e-spec.ts
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)