3

I am a newbie in unit testing and I have 2 files:

RestaurantReducer

import * as Const from '../constants/Const'

const RestaurantReducer = (state = {
    restaurantList: []
}, action) => {
    switch (action.type) {
        case Const.GET_RESTAURANT_LIST: {

            return {
                ...state,
                restaurantList: action.payload
            };
        }
    }
    return state;
};

export default RestaurantReducer;

and RestauntActions.js

export function getRestaurantList() {
    return dispatch => {
        axios({
            method: "GET",
            url: URLS.URL_RESTAURANT_LIST
        }).then((response) => {
            dispatch({
                type: CONST.GET_RESTAURANT_LIST,
                payload: response.data
            })
        })
    }
}

and my test:

describe('request reducer', () => {

    it('Default values', () => {
        expect(restReducer(undefined, {type: 'unexpected'})).toEqual({
          restaurantList: []
        });
    });

    // ---------------- Dont know how to check this -------------------
    it('Async data',async () => {

        expect(restReducer(undefined, {
            type: 'GET_RESTAURANT_LIST',
        })).toEqual({
            ...state,
            restaurantList: []
        });
    });
});

I do not know how to go about it. Can you check the connection or data that come from the server? Can such data simulate but they are dynamic.

vedsil
  • 137
  • 18
Przemek eS
  • 1,224
  • 1
  • 8
  • 21

1 Answers1

0

the basic idea you need to mock your dependency(axios call in the case). This answer describe how to do that.

I created the sample to illustrate the idea:

const axios = require('axios')
const assert = require('assert')
const moxios = require('moxios')


const asyncFunctionToTest = () => {
    // grabs length of google page body
    return axios({
        url: 'http://google.com',
        method: 'GET'
    })
    .then(resp => resp.data.length)
}



describe('async function', () => {
    beforeEach(function () {
        // import and pass your custom axios instance to this method
        moxios.install()
    })

    afterEach(function () {
        // import and pass your custom axios instance to this method
        moxios.uninstall()
    })
    it('returns propper body length', () => {
        const BODY = 'short string'
        const mocked = moxios.wait(function () {
            const request = moxios.requests.mostRecent()
            request.respondWith({
                status: 200,
                response: BODY
            })
        })
        return Promise.all([asyncFunctionToTest(), mocked]) // imported bit: you need to return promise somehow in your test
            .then(([result]) => {
                assert(result === BODY.length, result)
            })
    })
})
kharandziuk
  • 12,020
  • 17
  • 63
  • 121