1

I have a saga

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

That calls an API and with return value navigate to another screen passing the API call result (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 }))
  );
});

Since it's not actually running the API call response doesn't get defined.

I don't know what I should do to test this scenario.

How do I test the second step of my saga?

1 Answer 1

6

By default, the yield expression resolves to whatever it yielded. However, you can pass another value to the gen.next method and then the yield expression is resolved to what you passed there.

So this should do the trick (untested):

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 }))
);

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.