模拟axios请求开玩笑网络错误

时间:2017-11-08 20:01:32

标签: unit-testing redux axios jest

我正在尝试使用axios-mock和jest创建异步测试。

这是我的测试文件:

var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');

const middlewares = [thunk,axiosMiddleware]
const mockStore = configureMockStore(middlewares)

describe('async-actions', () => {

    var instance;
    var mock;

    beforeEach(function() {
         instance = axios.create();
         mock = new MockAdapter(instance);
    });

    afterEach(() => {
        mock.reset()
        mock.restore()
    })

    it('creates FETCH_BOOKINGS_SUCCESS when fetch bookings has been done', () => {

     mock
          .onGet('/bookings').reply(200, {
             data: [
                 { id: 1, name: 'test booking' }
             ]
         });

        const expectedActions = [
            {type: "FETCH_BOOKINGS_START" },
            {type: "FETCH_BOOKINGS_SUCCESS", }
        ]

        const store = mockStore({
            session: {
                token: {
                    token: "test_token"
                }
            }
        })

        return store.dispatch(actions.fetchBookingsTest())
            .then(
                () => {
                    expect(store.getActions()).toEqual(expectedActions)
                })


        // return of async actions
    })

})

我的行动:

export function fetchBookingsTest() {
    return (dispatch) => {
        dispatch(async.fetchDataStart(namedType));
        return dispatch(rest.get(BOOKINGS))
            .then(
                (data) => {
                    dispatch(async.fetchDataSuccess(data,namedType));
                },
                (error) => {
                    dispatch(async.fetchDataFailure(error,namedType));
                }
            )
    }
}

我有中间件设置,它使用redux商店中的身份验证令牌来获取每个请求。这就是我在模拟商店中设置“test_token”的原因。

当我运行此测试时,我会收到回复

[{"type": "FETCH_BOOKINGS_START"}, {"payload": [Error: Network Error], "type": "FETCH_BOOKINGS_FAILURE"}]

为什么我收到网络错误?我是否需要使用Jest进行更多设置以避免使用mock-axios进行身份验证?

0 个答案:

没有答案