【问题标题】:How to test a Saga with an API call?如何使用 API 调用测试 Saga?
【发布时间】:2017-08-14 15:06:43
【问题描述】:

我有一个传奇

export function* mysaga(api, action) {
  const response = yield call(api.service, action);
  yield put(NavActions.goTo('Page', { success: response.ok }));
}

调用 API 并返回值导航到另一个屏幕,传递 API 调用结果 (response.ok)。

it('test', () => {
  // ...

  const gen = mysaga(api, action);
  const step = () => gen.next().value;

  // doesn't actually run the api
  const response = call(api.service, {});

  expect(step()).toMatchObject(response); // ok

  // error, Cannot read property 'ok' of undefined
  expect(step()).toMatchObject(
    put(NavActions.goTo('Page', { success: response.ok }))
  );
});

因为它实际上并没有运行 API 调用 response 没有得到定义。

我不知道我应该做些什么来测试这个场景。

如何测试我的传奇的第二步?

【问题讨论】:

    标签: react-native jestjs redux-saga


    【解决方案1】:

    默认情况下,yield 表达式解析为它产生的任何内容。但是,您可以将另一个值传递给 gen.next 方法,然后将 yield 表达式解析为您在那里传递的值。

    所以这应该可以解决问题(未经测试):

    const gen = rootSaga(api, action);
    const step = (val) => gen.next(val).value;
    
    const mockResponse = { ok: true };
    const response = call(api.service, {});
    
    expect(step(mockResponse)).toMatchObject(response); // ok
    
    expect(step()).toMatchObject(
      put(NavActions.goTo('Page', { success: true }))
    );
    

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 2016-06-09
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 2018-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多