mercredi 30 septembre 2020

Redux saga testing with api call using jest

I am trying to test my saga function that have an api call. However, I think I made a mistake or something wrong where the expected and the received values are different. expected: is the data and the correct action type received: an error with the failure action type. Please refer to the picture and the code of my saga and saga.test. I would appreciate if someone can help out and guide me to the correct way for testing the saga with an api call.

Saga testing results

Saga.js

import { failure, loadBrowseLocationsSuccess, loadBrowseClassificationsSuccess } from "./actions";
import ApiConstants, * as actionTypes from "./constants";
import { all, put, takeLatest, call } from "redux-saga/effects";
import ApiService from "../../services/api_service";

export default function* rootSalarySaga() {
  yield all([
    takeLatest(actionTypes.LOAD_BROWSE_LOCATIONS_CLASSIFICATION, loadBrowseLocationsClassificationsData),
  ]);
}


export function* loadBrowseLocationsClassificationsData() {
  const requestUrl = ApiConstants.BROWSE_LOCATIONS_CLASSIFICATIONS_URL;

  const res = yield ApiService.Get(requestUrl);
  if (res.status === 200) {
    yield put(loadBrowseLocationsSuccess(res.data[locations]));
    yield put(loadBrowseClassificationsSuccess(res.data[classifications]));
  } else {
    yield put(failure(res.data));
  }
}

Saga.test

import { put, call } from "redux-saga/effects";
import { loadBrowseLocationsClassificationsData } from "../saga";
import ApiService from "../../../services/api_service";
import ApiConstants, * as actionTypes from "../constants";
import { failure, loadBrowseLocationsSuccess, loadBrowseClassificationsSuccess } from "../actions";

describe("saga testing for browse container", () => {
  it("should dispatch action LOAD_BROWSE_LOCATIONS_SUCCESS with results from loadBrowseLocationsClassificationsData", () => {
    const generator = loadBrowseLocationsClassificationsData();
    const requestUrl = ApiConstants.BROWSE_LOCATIONS_CLASSIFICATIONS_URL;
    const response = { data: { results: "mockData" } };

    expect(generator.next().value).toEqual(ApiService.Get(requestUrl));
    expect(generator.next(response).value).toEqual(put(loadBrowseLocationsSuccess("mockData")));
    expect(generator.next(response).value).toEqual(put(loadBrowseClassificationsSuccess("mockData")));
    expect(generator.next()).toEqual({ done: true, value: undefined });
  });
});

for api_service.get function is just an axios function.

import axios from "axios";

class ApiService {
 static Get(requestUrl) {
    return axios
      .get(requestUrl)
      .then((response) => {
        return response;
      })
      .catch((error) => {
        return error.response;
      });
  }
}

export default ApiService;

Aucun commentaire:

Enregistrer un commentaire