我正在尝试测试失败操作的效果,并在Brian Love's博客之后对其进行了建模。但是,当我测试失败时,我会收到一条错误消息,提示它期望成功执行操作。
这是我的代码:
search.service.ts:
save(acronym: Acronym) {
if (acronym.id) {
return this.update(acronym);
} else {
return this.add(acronym);
}
}
add(acronym: Acronym) {
return this.db.collection(config.acronyms).add(acronym).then(() => this.search(acronym.code, acronym.project));
}
update(acronym: Acronym) {
return this.db.collection(config.acronyms).doc(acronym.id).update(acronym).then(() => this.search(acronym.code, acronym.project));
}
effect.ts
@Effect()
saveAcronym$ = this.actions$.pipe(
ofType(acronymActions.SAVE_ACRONYM),
map((action: acronymActions.SaveAcronym) => action.payload),
mergeMap((payload) => {
this._searchService.save(payload);
return of(payload);
}),
map(data => new acronymActions.SaveAcronymSuccess(data)),
catchError(error => of(new acronymActions.SaveAcronymFail(error)))
);
effect.spec.ts
it("should return a SaveAcronymFail action, with an error, on fail", () => {
const payload = {code: "SME", project: "SWAN"};
const action = new fromActions.SaveAcronym(payload);
const error = new Error();
const result = new fromActions.SaveAcronymFail(error);
actions = hot("-a", {a: action});
const response = cold("-#|", {}, error);
const expected = cold("--(b|)", {b: result});
searchService.save = jest.fn(() => response);
expect(effects.saveAcronym$).toBeObservable(expected);
});
action.ts
export class SaveAcronymFail implements Action {
readonly type = SAVE_ACRONYM_FAIL;
constructor(public payload: Error) {}
}
reducer.ts:
case AcronymActions.SAVE_ACRONYM_FAIL:
return {...state, loading: false, loaded: true};
错误:
expect(received).toEqual(expected)
Expected value to equal:
[{"frame": 20, "notification": {"error": undefined, "hasValue": true, "kind": "N", "value": {"payload": [Error], "type": "[ACRONYM] Save Fail"}}}, {"frame": 20, "notification": {"error": undefined, "hasValue": false, "kind": "C", "value": undefined}}]
Received:
[{"frame": 10, "notification": {"error": undefined, "hasValue": true, "kind": "N", "value": {"payload": {"code": "SME", "project": "SWAN"}, "type": "[ACRONYM] Save Success"}}}]
我尝试修改框架,但是没有运气。
答案 0 :(得分:-2)
尝试此代码 effect.spec.ts
it('should return an fail action, with an error, on failure', () => {
const user = generateUser();
const action = new AddData({ user });
const error = new Error();
const outcome = new AddDatafail({ error });
actions = hot('-a|', { a: action });
const response = cold('-#|', {}, error);
const expected = cold('--(b|)', { b: outcome });
serService.saveSampleData = jest.fn(() => response);
expect(effects.AddData).toBeObservable(expected););
});