jfairbank / redux-saga-test-plan

Test Redux Saga with an easy plan.
http://redux-saga-test-plan.jeremyfairbank.com
MIT License
1.25k stars 127 forks source link

Testing if statement #368

Open cologneto opened 3 years ago

cologneto commented 3 years ago

I want to test the following saga:

function* fetchCustomerById({ id }) {
  try {
    const fetchedCustomer = yield call(rest.getCustomerById, id);
    if (fetchedCustomer) {
      yield put(fetchCustomerSuccess(fetchedCustomer));
    }
  } catch (error) {
    yield put(fetchError(error));
  }
}

I'm trying this:

  it('testing fetchCustomerById', () => {
    const id = '123';
    const saga = testSaga(tests.fetchCustomerById, id);

    saga
      .next()
      .call(rest.getCustomerById, undefined)
      .next(true)
      .put(fetchCustomerSuccess(undefined))
      .next()
      .isDone();
  });

And the test doesn't pass. Got this error: Assertion 2 failed: put effects do not match

Expected
--------
{ '@@redux-saga/IO': true,
  combinator: false,
  type: 'PUT',
  payload:
   { channel: undefined,
     action: { type: 'FETCH_CUSTOMER_SUCCESS', payload: undefined } } }

Actual
------
{ '@@redux-saga/IO': true,
  combinator: false,
  type: 'PUT',
  payload:
   { channel: undefined,
     action: { type: 'FETCH_CUSTOMER_SUCCESS', payload: true } } }

  50 |       .call(rest.getCustomerById, undefined)
  51 |       .next(true)
> 52 |       .put(fetchCustomerSuccess(undefined))
     |        ^
  53 |       .next()
  54 |       .isDone();
  55 |   });

  at assertSameEffect (node_modules/redux-saga-test-plan/lib/testSaga/assertSameEffect.js:18:11)
  at Object.put (node_modules/redux-saga-test-plan/lib/testSaga/index.js:49:37)
  at Object.<anonymous> (src/appRedux/sagas/iObserverSagas/CustomerSaga.test.js:52:8)

Is there a way to pass undefined payload?

Thanks, Georgi

kuk941025 commented 3 years ago

You can mock call(rest.getCustomerById, id). Heres the test code I would write. (Not tested).

import {expectSaga} from 'redux-saga-test-plan';
import {call} from 'redux-saga-test-plan/matchers';

test('fetchCustomerById', () => 
  expectSaga(fetchSaga)
  .provide([[call.fn(rest.getCustomerById), true]])
  .put(fetchCustomerSuccess(expectedCustomer)
  .dispatch(action.fetchCustomerById())
  .silentRun());

In the test, reset.getcustomerById would return true. Read more about static providers on document