如何通过API调用测试Saga?

时间:2017-08-14 15:06:43

标签: react-native jestjs redux-saga

我有一个传奇

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,因此无法定义。

我不知道应该怎么做来测试这种情况。

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

1 个答案:

答案 0 :(得分:4)

默认情况下,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 }))
);