簡體   English   中英

測試異步方法以與開玩笑反應

[英]Testing async method in react with jest

我是單元測試的新手,我有 2 個文件:

餐廳減速機

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 check this -------------------
    it('Async data',async () => {

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

我不知道該怎么做。 您可以檢查來自服務器的連接或數據嗎? 這樣的數據可以模擬,但它們是動態的。

你需要模擬你的依賴的基本想法(在這種情況下是 axios 調用)。 這個答案描述了如何做到這一點

我創建了示例來說明這個想法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM