gpt4 book ai didi

reactjs - React + Redux-Observable 超时大理石测试

转载 作者:行者123 更新时间:2023-12-04 17:43:17 25 4
gpt4 key购买 nike

我正在使用 React 和 Redux Observables 创建一个网络应用程序,我想为我的一个史诗的超时场景创建一个单元测试。

这是史诗:

export const loginUserEpic = (action$: ActionsObservable<any>, store, { ajax, scheduler }): Observable<Action> =>
action$.pipe(
ofType<LoginAction>(LoginActionTypes.LOGIN_ACTION),
switchMap((action: LoginAction) =>
ajax({
url,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: { email: action.payload.username, password: action.payload.password },
}).pipe(
timeout(timeoutValue, scheduler),
map((response: AjaxResponse) => loginSuccess(response.response.token)),
catchError((error: Error) => of(loginFailed(error))),
),
),
);

这是我的测试:

  it('should handle a timeout error', () => {
// My current timeout value is 20 millseconds
const inputMarble = '------a';
const inputValues = {
a: login('fake-user', 'fake-password'),
};

const outputMarble = '--b';
const outputValues = {
b: loginFailed(new Error('timeout')),
};

const ajaxMock = jest.fn().mockReturnValue(of({ response: { token: 'fake-token' } }));
const action$ = new ActionsObservable<Action>(ts.createHotObservable(inputMarble, inputValues));
const outputAction = loginUserEpic(action$, undefined, { ajax: ajaxMock, scheduler: ts });

// I am not sure what error to expect here...
ts.expectObservable(outputAction).toBe(outputMarble, outputValues);
ts.flush();
expect(ajaxMock).toHaveBeenCalled();
});

我预计 Epic 会抛出超时错误,因为我的超时值为 20 毫秒,而 Observer 在发出值之前延迟了 60 毫秒。然后我会接受这个错误并在最后比较它以使测试通过。

不幸的是,没有抛出超时错误。我做错了什么吗?

最佳答案

调用 ajax() 后,您在链中使用了 timeout,它只返回 of({ ... }) (ajaxMock) 所以 timeout 永远不会被触发,因为 of 会立即发出。

如果你想测试 timeout 运算符,你需要将 delay 添加到 ajaxMock 中:

const ajaxMock = () => of({ response: { token: 'fake-token' } }).pipe(delay(30, ts));

这是您的演示:https://stackblitz.com/edit/rxjs6-demo-pha4qp?file=index.ts

如果登录请求从 60 开始,并且您添加了 30 延迟,那么在 80 时您将收到 TimeoutError。

[0: Object
frame: 80
notification: Notification
error: undefined
hasValue: true
kind: "N"
value: Object
error: Error
message: "Timeout has occurred"
name: "TimeoutError"
]

关于reactjs - React + Redux-Observable 超时大理石测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53427965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com