【发布时间】:2022-12-10 01:20:39
【问题描述】:
我们正在为应用程序使用 jest 编写单元测试,我们希望在单元测试中涵盖 saga。但是,我们正在努力对 saga 进行单元测试。
在编写单元测试时,我们在 inventory.saga.spec.ts 文件中发布 InventoryEvent 并期望调用 inventory.saga.ts 中的 inventory() 但是 saga 不会收到通过测试文件发布的事件,而当我们发布相同的文件时通过应用程序事件然后在传奇中接收事件。
请帮助我确定 saga 未收到通过测试文件发布的事件的问题。
目前的申请流程是
- 库存处理程序发布 InventoryEvent
- saga 充当事件侦听器并侦听 InventoryEvent 并调用 InventoryCacheCommand
下面是代码sn-p
库存.handler.ts
await this.eventBus.publish(new InventoryEvent(inventoryData));库存.event.ts
import { IEvent } from '@nestjs/cqrs'; import { InventoryStatusInterface } from '../../../interface/inventory.interface'; export class InventoryEvent implements IEvent { constructor(public readonly inventoryData: InventoryStatusInterface) {} }库存.saga.ts
import { Injectable } from '@nestjs/common'; import { ICommand, ofType, Saga } from '@nestjs/cqrs'; import { map, Observable } from 'rxjs' import { createLog } from '../../infrastructure/service/utils/logger'; import { InventoryCacheCommand } from '../commands/impl/inventory-cache.command'; import { InventoryEvent } from '../events/impl/inventory.event'; @Injectable() export class InventorySaga { private logger = createLog(InventorySaga.name); @Saga() inventory = (events$: Observable<any>): Observable<ICommand> => { return events$.pipe( ofType(InventoryEvent), map((event: InventoryEvent) => { this.logger.info('received inventory event to upsert inventory cache: ',event.inventoryData); return new InventoryCacheCommand(event.inventoryData); }) ); } }清单.saga.spec.ts
import { Test, TestingModule } from '@nestjs/testing'; import { InventorySaga } from './inventory.saga'; import { InventoryEvent } from '../events/impl/inventory.event'; import { CommandBus, EventBus } from '@nestjs/cqrs'; import { InventoryCacheCommand } from '../commands/impl/inventory-cache.command'; import { Observable } from 'rxjs'; jest.mock('../commands/impl/inventory-cache.command') describe('InventorySaga', () => { let saga: InventorySaga; let eventBus: EventBus beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ InventorySaga, EventBus, CommandBus ], }).compile(); saga = module.get<InventorySaga>(InventorySaga); eventBus = module.get<EventBus>(EventBus) }); describe('saga', () => { it('should publish InventoryEvent', async () => { const inventoryData = [ { sku: 'TH4344-43-L', qty: 3, }, { sku: 'TH4344-43-S', qty: 55, }, { sku: 'TH4344-43-XL', qty: 55, }, ]; const spy = jest.spyOn(saga, 'inventory'); await eventBus.publish(new InventoryEvent(inventoryData)); expect(spy).toBeCalled() }) }) });
【问题讨论】:
标签: javascript unit-testing jestjs nestjs saga