reactjs - Jest mock 传奇延迟

标签 reactjs redux jestjs redux-saga react-testing-library

问题

我正在使用 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/

相关文章:

javascript - ReactClassInterface : You are attempting to define `constructor` on your component more than once. 此冲突可能是由于 mixin

reactjs - WebSocket 连接到 'ws:<URL>/_next/webpack-hmr' 失败 : WebSocket is closed before the connection is established

javascript - React 上下文 - 'contextType' 未定义

reactjs - 在 createTheme 中覆盖 Box 组件

reactjs - 在 componentDidMount 上调度一个 Action (react/redux)

angular - 解决 Action 创建者中的异步函数

jestjs - 数据驱动的 Jestjs 测试

javascript - React-redux connect HOC 作为类装饰器,@connect

javascript - 火力地堡 'A network error (such as timeout, interrupted connection or unreachable host) has occurred.'

jestjs - 用 Jest 测试两个环境