vendredi 15 janvier 2021

I want to perform a getWeather aync test in my application using jest

I want to perform an async action test in my application that takes a city name and gives back the data. I have written the test for loading and error but I am slightly confused on how to perform testing on API calls using async function.

WeatherAction.tsx

import { ThunkAction } from 'redux-thunk';
import { RootState } from '..';
import { WeatherAction, WeatherData, WeatherError, GET_WEATHER, SET_LOADING, SET_ERROR } from '../types';

export const getWeather = (city: string): ThunkAction<void, RootState, null, WeatherAction> => {
  return async dispatch => {
    try {
      const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=apival`);

      if(!res.ok) {
        const resData: WeatherError = await res.json();
        throw new Error(resData.message);
      }

      const resData: WeatherData = await res.json();
      dispatch({
        type: GET_WEATHER,
        payload: resData
      });
    }catch(err) {
      dispatch({
        type: SET_ERROR,
        payload: err.message
      });
      console.log(err)
    }
  }
}

export const setLoading = (): WeatherAction => {
  return {
    type: SET_LOADING
  }
}

export const setError = (): WeatherAction => {
  return {
    type: SET_ERROR,
    payload: ''
  }
}

Below is my weatherAction.test.ts

import * as weather from "../actions/weatherActions";
import * as type from "../types";
import "cross-fetch/polyfill";

import configureMockStore from "redux-mock-store";
import thunk from "redux-thunk";
import fetchMock from "fetch-mock";

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

test("test the value of loading", () => {
  console.log(weather);
  const loading = " Loading";
  const expectedAction = {
    type: type.SET_LOADING
  };
  expect(weather.setLoading(loading)).toEqual(expectedAction);
});

test("test error", () => {
  const error = " ";
  const expectedAction = {
    type: type.SET_ERROR,
    payload: ""
  };
  expect(weather.setError(error)).toEqual(expectedAction);
});

And store in case it is required.

import { createStore, applyMiddleware, combineReducers } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';

import weatherReducer from './reducers/weatherReducer';
import alertReducer from './reducers/alertReducer';

const rootReducer = combineReducers({
  weather: weatherReducer,
  alert: alertReducer
});

const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

export type RootState = ReturnType<typeof rootReducer>;

export default store;

Aucun commentaire:

Enregistrer un commentaire