Redux Sagas Unit Testing

I followed the documentation for Redux Sagas and created a suite of tests, however they seem very fragile to me. Whenever I update the logic in any of my sagas, my tests fail. It causes alarm in my head and makes me think that I am doing something wrong.

Here is an example saga that communicates with the API to load a user profile and save it in Redux state:

export function* userAuthCheck() {
    try {
        yield put({ type: START_HTTP });

        const me = yield apply(user, user.me);
        const organisations = yield apply(user, user.organisations, [me.body.data.id]);

        yield put({
            type: USER_AUTH_SUCCESS,
            redirect: true,
            state: {
                account: me.body.data,
                organisations: organisations.body.data,
            },
        });
    } catch (error) {
        yield put({ type: USER_AUTH_REFRESH });
    } finally {
        yield put({ type: COMPLETE_HTTP });
    }
}

Here's the relevant test:

it('can successfully call the API', () => {
    const generator = userAuthCheck();

    expect(generator.next().value).toEqual(put({ type: START_HTTP }));
    expect(generator.next().value).toEqual(call(user.me));

    expect(generator.next().value).toEqual(put({
        type: USER_AUTH_SUCCESS,
        state: { user: undefined },
    }));

    expect(generator.next().value).toEqual(put({ type: COMPLETE_HTTP }));
});

You may have noticed that the test will indeed fail if it is running because I did not update it since I made some recent updates for the saga. This is what started me on this path of thought.

? , API , ?

: https://redux-saga.imtqy.com/redux-saga/docs/introduction/BeginnerTutorial.html

+4
2

, , - :

import configureMockStore from "redux-mock-store";
import createSagaMiddleware from "redux-saga";
import rootSaga from "pathToRootSaga/rootSaga";
import {userAuthCheckActionCreator} from "yourPath/UserActionCreators"; 

it('can successfully call the API', () => {
  const sagaMiddleware = createSagaMiddleware();
  const mockStore = configureMockStore([sagaMiddleware]);
  const store = mockStore({});
  sagaMiddleware.run(rootSaga);

  const expectedActions = [
    {
      type: START_HTTP
    },
    {
      type: USER_AUTH_SUCCESS,
      redirect: true,
      state: {
          account: me.body.data,
          organisations: organisations.body.data,
      }
    },
    { 
      type: COMPLETE_HTTP 
    }
  ];

  store.dispatch(userAuthCheckActionCreator());
  expect(store.getActions()).toEqual(expectedActions);
});

, , , . , , Saga , .

+1

Source: https://habr.com/ru/post/1669302/


All Articles