我不能在Jest/Angular应用程序中正确地模拟衍生的Observable流。
首先,我们需要测试NgRx的效果。
export const cancel$ = createEffect(
(
actions$ = inject(Actions),
tradingControllerService = inject(TradingControllerService),
wsService = inject(WebSocketService),
store = inject(Store),
) => {
return actions$.pipe(
ofType(pendingOrdersActions.cancel),
switchWith(() => store.select(WebTraderSelectors.selectTradingAccountId)),
switchMap(([{ id }, tradingAccountId]) => {
const referenceId = TradingMathFunctions.generateReferenceId();
return tradingControllerService.cancelOrder(id, <number>tradingAccountId, referenceId);
}),
switchMap(() => wsService.cancelPendingTrade$),
map(({ tradeId }) => pendingOrdersActions.cancelSuccess({ id: tradeId })),
);
},
{ functional: true },
);
字符串
测试表明,除了最后一个流wsService.cancelPendingTrade$之外,所有行都被正确地模拟。
主要的问题是,这个应该被模仿的流是从ReplaySubject派生出来的,它是一个类属性。
cancelPendingTrade$ = this.message$.pipe(
filter(WebSocketFunctions.isCancelPendingTradeMessage),
map(WebSocketFunctions.getCancelPendingTradeData),
filter(Boolean),
);
webSocket$: WebSocketSubject<Cli2Ser | Ser2Cli | MockCli2Ser> | undefined;
message$ = new ReplaySubject<Ser2Cli>(1);
型
我尝试了如下测试
describe('PendingOrdersEffects', () => {
let tradingControllerServiceMock: MockProxy<TradingControllerService>;
let storeMock: MockProxy<Store>;
let wsServiceMock: MockProxy<WebSocketService>;
beforeEach(() => {
storeMock = mock<Store>({
select: jest.fn().mockReturnValueOnce(of(1234)),
});
tradingControllerServiceMock = mock<TradingControllerService>({
cancelOrder: jest.fn(),
});
wsServiceMock = mock<WebSocketService>();
});
describe('cancel$', () => {
it('should return `cancelSuccess` action', () => {
const spy = jest.fn();
const actions$ = of(pendingOrdersActions.cancel({ id: 1 }));
tradingControllerServiceMock.cancelOrder.mockReturnValueOnce(
of({ data: { orderId: 1 } } as unknown as HttpEvent<StandardResponseOrderResult>),
);
// Mock this stream here
PendingOrdersEffects.cancel$(actions$, tradingControllerServiceMock, wsServiceMock, storeMock)
.pipe(take(1))
.subscribe(spy);
expect(spy).toHaveBeenCalledWith(pendingOrdersActions.cancelSuccess({ id: 1 }));
});
});
型
1条答案
按热度按时间fzwojiic1#
实际的mocking非常简单。我只需要直接设置一个流到这个属性。
字符串