问题
我正在使用 redux-saga、jest、redux-mock-store 和 react-testing-library,我尝试测试一个对服务器进行轮询直到响应状态得到解决的 saga。 在 saga 中,我使用 redux-saga 延迟函数来创建轮询间隔。
const INTEVAL_TIME = 3000;
function* saga(action) {
try {
yield delay(INTEVAL_TIME);
while (true) {
const { data } = yield call(apiCall);
if (data.status === 'success') {
yield put(success());
break;
}
if (data.status === 'failure') {
yield put(failure());
break;
}
yield delay(INTEVAL_TIME );
}
} catch (error) {
yield put(failure());
}
}
我如何在测试中 self 模拟延迟不等待 3 秒(可能将延迟设置为 0 或立即解决)。 例如,这是我的测试
it('some test', async () => {
const { getByTestId } = render(<MyComponent />);
userEvent.click(getByTestId('button');
await waitFor(() => {
expect(store.getActions()).toEqual(succesPayloadMock);
});
});
最佳答案
我不确定我是否完全理解你的问题,但是当涉及到 redux saga 时,我使用库 redux-saga-test-plan为了集成延迟模拟,我执行以下操作:
const provideDelay = ({ fn }: FnObj, next: () => void) =>
fn.name === "delayP" ? null : next();
return expectSaga(function)
.provide([{ call: provideDelay }])
.call(anotherFunction)
.run();
关于reactjs - Jest mock 传奇延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64970555/