mercredi 17 avril 2019

I'm struggling to test this redux saga

I'm relatively new to redux-saga and struggling to test this code:

import { normalize } from 'normalizr';

export function* normalizeResponse(denormalized, schema) {
  const normalized = yield call(normalize, denormalized, schema);
  return normalized;
}

export function* request(apiFn, action, schema) {
  try {
    yield put(requestStart({ type: action.type }));
    const denormalized = yield call(apiFn, action.payload, action.meta);
    const normalized = yield call(normalizeResponse, denormalized, schema);
    yield put(requestSuccess({ type: action.type }));
    return normalized;
  } catch (e) {
    if (__DEV__ && !__TEST__) {
      Alert.alert('Something went wrong');
      console.log(`Error in request saga: ${action.type}`, e);
    }
    if (action.type) {
      const payload = { type: action.type, error: e };
      const meta = action.payload || {};
      yield put(requestFailure(payload, meta));
    }
  }
}

export function* photosShow() {
  while (true) {
    const action = yield take(t.PHOTOS_SHOW);
    const normalized = yield call(request, api.show, action, {
      photo: schema.photo,
    });
    if (normalized) yield put(setEntities(normalized));
  }
}

Online, I've found a number of redux saga test packages and some tutorials but none of them seems to cover much more than the basics. Here is the step-by-step of how the saga works:

  • photosShow is called with a Flux standard action, with payload of { id: 1}
  • This will call the generator request which is a utility function to make an API request and then normalise the response.
  • Firstly, a requestStart action will be triggered
  • Then the api endpoint will be called
  • If successful, a requestSuccess action will be triggered
  • The response will be then be normalised using normalizr
  • And then stored in the redux state with setEntities (back in photosShow)

Any help moving forward with how to go about this would be much appreciated.

Aucun commentaire:

Enregistrer un commentaire