这是我对单元测试效果的第一种方法,我不知道如何为我的 Store Dependent Effect 编写测试,这是效果代码:
validaCellulare$ = createEffect(() =>
this.actions$.pipe(
ofType(checkPIvaSuccess, inviaOtpIntent),
concatMap(action => of(action).pipe(
withLatestFrom(this.onboardingSelector.modelStep1$)
)),
exhaustMap(([action, datiStep1]) =>
this.onboardingService.postValidateCellulare(datiStep1.cellulare, OnboardingFactory.getCellulareWidgetId(this.centricoState.widgetStep1)).pipe(
map((res) => {
if (!!res && res.result.status === ApplicationParams.StatusResponse.success) {
if (action.type === checkPIvaSuccess.type) {
this.modalService.open(ApplicationParams.templateNames.OTP, {
isClosable: false
});
}
return inviaOtpSuccess();
}
return action.type === checkPIvaSuccess.type ? errorThrowing({statusCode: res.result.statusCode}) : inviaOtpIntentError();
}
),
catchError(() => of(inviaOtpIntentError()))
)
)
));
在我的单元测试之上:
it('checkPIvaSuccess should dispatch inviaOtpSuccess, on success call postValidateCellulare and open modal OTP', () => {
store.setState({onboarding: {modelStep1: {partitaIva: '12345678960', email: 'fasdfa@sdf.ati', cellulare: '1204014001', flagPrivacy: true}}});
const mockResponse = Mock.onboarding.validate.cellulare[1].body;
const action = checkPIvaSuccess({guid: '1592314141805665835746662667089'});
const completion = inviaOtpSuccess();
actions$ = hot('a', {a: action});
const response = cold('(a|)', {a: mockResponse});
const expected = cold('b', {b: completion});
onboardingService.postValidateCellulare = jest.fn(() => response);
expect(effects.validaCellulare$).toBeObservable(expected);
expect(modalService.open).toHaveBeenCalledWith(ApplicationParams.templateNames.OTP, {isClosable: false});
});
在测试环境中调试此代码看起来像是在 concatMap 中被阻塞并立即停止而不调用内部服务器调用 postValidateCellulare。有人可以帮助我吗?
--------------- 编辑现在它工作 -------------
感谢@BenLesh,我仔细检查了我的代码,但我错过了设置我的appKeyStore = 'entityCache'
. 因此,按照以下方式替换规范完全有效:
it('checkPIvaSuccess should dispatch inviaOtpSuccess, on success call postValidateCellulare and open modal OTP', () => {
store.setState({[appStoreKey]: {onboarding: {modelStep1: {partitaIva: '12345678960', email: 'fasdfa@sdf.ati', cellulare: '1204014001', flagPrivacy: true}}}});
const mockResponse = Mock.onboarding.validate.cellulare[1].body;
const action = checkPIvaSuccess({guid: '1592314141805665835746662667089'});
const completion = inviaOtpSuccess();
actions$ = hot('a', {a: action});
const response = cold('(a|)', {a: mockResponse});
const expected = cold('b', {b: completion});
onboardingService.postValidateCellulare = jest.fn(() => response);
expect(effects.validaCellulare$).toBeObservable(expected);
expect(modalService.open).toHaveBeenCalledWith(ApplicationParams.templateNames.OTP, {isClosable: false});
});