【问题标题】:Mocking saga delay in jest开玩笑的传奇故事延迟
【发布时间】:2020-11-23 14:39:22
【问题描述】:

问题

我正在使用 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());
  }
}

   

我如何在测试中自我模拟延迟不等待 3 秒(也许将延迟设置为 0 或立即解决)。 例如,这是我的测试

it('some test', async () => {
 const { getByTestId } = render(<MyComponent />);
 userEvent.click(getByTestId('button');

 await waitFor(() => {
      expect(store.getActions()).toEqual(succesPayloadMock);
     });
  });

【问题讨论】:

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


    【解决方案1】:

    我不确定我是否完全理解您的问题,但是当谈到 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();
    

    【讨论】:

      【解决方案2】:

      这个问题的解决方法其实在redux-sagahereBeginner Tutorial中都有讨论。简而言之,您希望产生 call 效果,而不是直接调用 delay

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-05
        • 2018-01-10
        • 2022-08-07
        • 2020-11-22
        • 1970-01-01
        • 1970-01-01
        • 2014-03-18
        • 1970-01-01
        相关资源
        最近更新 更多