5

我正在尝试在 redux 测试我的异步操作,但我没有得到它。

我正在使用 nock 和 axios,所以我试图从 axios get 接收响应数据来测试我的操作:

describe('Async Actions', () => {
    afterEach(() => {
        nock.cleanAll();
    });

    it('should load transmissors', (done) => {
        const localStorage = {
            token: 'a9sd8f9asdfiasdf'
        };
        nock('https://tenant.contactto.care')
                .get('/api/clients/1/transmissors/', {
                     reqheaders: { 'Authorization': "Token " + localStorage.token } 
                })
                .reply(200, { data: [
                    {
                        "id": 12,
                        "zone": "013",
                        "client": 1,
                        "description": "pingente",
                        "identifier": "",
                        "general_info": ""
                    },
                    {
                        "id": 15,
                        "zone": "034",
                        "client": 1,
                        "description": "colar",
                        "identifier": "",
                        "general_info": ""
                    }
                ]});

        axios.get(`/api/clients/1/transmissors/`, {
            headers: { 'Authorization': "Token " + localStorage.token },
        }).then(transmissors => { 
                console.log(transmissors);
        }).catch(error => {
            throw(error);
        })
        done();
    });
});

这是我的行动:

 export function loadTransmissors(clientId){
        return function(dispatch){
            axios.get(`/api/clients/${clientId}/transmissors/`, {
                headers: { 'Authorization': "Token " + localStorage.token },
            }).then(transmissors => { 
                    dispatch(loadTransmissorsSuccess(transmissors.data, clientId));
            }).catch(error => {
                throw(error);
            })
        }
    }

但我在 console.log 收到此错误:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 3): SyntaxError

我从 Dan Abramov 那里找到了这个答案: How to unit test async Redux actions to mock ajax response

https://github.com/reactjs/redux/issues/1716

有谁知道如何使用 redux-thunk.withExtraArgument 进行测试?

提前致谢。

4

1 回答 1

1

我通过 redux thunk https://github.com/gaearon/redux-thunk#injecting-a-custom-argument的参数解决了我的问题注入 axios

所以我在我的商店改变了我的 redux thunk:

applyMiddleware(thunk)

为了

applyMiddleware(thunk.withExtraArgument({ axios }))

所以我在动作中更新了我的异步返回函数来自:

return (dispatch) => {
   ...
}

至:

return (dispatch, getState, { axios }) => {
   ...
}

在我的 actions.test 中,我用 Promise 模拟了一个 API:

const axios = {
        get: (url,params) => Promise.resolve({data: transmissors})
}

在 redux thunk 处注入:

    const middleware = [thunk.withExtraArgument({axios})];
    const mockStore = configureMockStore(middleware);

    function asyncActions () {
      return dispatch => {
        return Promise.resolve()
          .then(() => dispatch(transmissorsActions.loadTransmissors(1)))
      }
    }

我使用函数 asyncActions 来测试我在商店中的操作:

it('should load transmissors', (done) => {  
        const expectedAction = { type: types.LOAD_TRANSMISSORS_SUCCESS,  transmissors, clientId};

        const store = mockStore({transmissors: [], expectedAction});
        store.dispatch(asyncActions()).then(() => {
            const action = store.getActions();
            expect(action[0].type).equal(types.LOAD_TRANSMISSORS_SUCCESS);
            expect(action[0].transmissors).eql(transmissors);
            expect(action[0].clientId).equal(1);
        });
        done();

    });

您可以通过此示例获得有关 redux-mock-store 的更多信息: https ://github.com/arnaudbenard/redux-mock-store/blob/master/test/index.js

于 2017-01-30T17:36:22.827 回答