测试异步方法与jest反应

时间:2017-09-13 12:05:36

标签: javascript reactjs jestjs

我是单元测试的新手,有2个文件:

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;

和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
            })
        })
    }
}

和我的测试:

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

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

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

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

我不知道如何去做。你能检查一下来自服务器的连接或数据吗?这些数据可以模拟,但它们是动态的。

1 个答案:

答案 0 :(得分:0)

模拟依赖关系所需的基本思想(在案例中为axios调用)。 This answer describe how to do that

我创建了示例来说明这个想法:

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)
            })
    })
})