我得到TypeError:无法读取属性'然后'当我尝试测试异步操作时未定义

时间:2017-08-08 22:46:47

标签: reactjs react-redux axios redux-thunk reactjs-testutils

我在reactjs中测试异步操作时遇到问题。 这是我的代码:

export function fillStoryBoard(snippetsLink, channel, uniqueStoryObj, isUniqueStorySearch) {

return function(dispatch){
        for (var i = 0; i < snippetsLink.length; i++) {
            loadStorySnippet(channel, snippetsLink[i], (i + 1),dispatch);
        }
    }
 }

function loadStorySnippet(channel,snippetsLink,indexValue,dispatch){
    return axios.get(ServiceUrls.prototype.getServicesDfltUrl()+snippetsLink)
        .then(response => {
            dispatch({
                type: "FILL_STORYBOARDS",
                payload: {
                    "channelName": channel,
                    "storiesSnippet": response.data,
                    "order":indexValue
                }
            });
        }).catch(function(response){

    });
 }

所以我的asnc调用是在一个没有导出的函数中,并且有一个函数在for循环中调用这个asnc函数。

现在这是我的测试:

it('should dispatch type: FILL_STORYBOARDS with what is returned from server as a payload', () => {
    nock(ServiceUrls.prototype.getServicesDfltUrl())
        .get('/snippet/111')
        .reply(200, {"id":1,"headline":"",
            "label":"Other",
            "imgUrl":"",
            "postDate":0});


    const expectedActions = [
        { "type": "FILL_STORYBOARDS","payload": { "channel": "",
            "storiesSnippet": {"id":1,"headline":"",
                "label":"Other","imgUrl":"" +
                "",
                "postDate":0},
            "order":1 } }
    ]
    const store = mockStore();
    return store.dispatch(fillStoryBoard(["snippet/111"], "")).then(() => {
        expect(store.getActions()[0].type).to.equal(expectedActions[0].type);
    })
})

现在问题是当我运行测试时:

TypeError: Cannot read property 'then' of undefined

知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

fillStoryBoard返回的thunk函数未返回承诺,因此您无法.then离开它。

尝试这样的事情:

return function(dispatch){
  var promises = [];
  for (var i = 0; i < snippetsLink.length; i++) {
      promises.push(loadStorySnippet(channel, snippetsLink[i], (i + 1),dispatch));
  }
  return Promise.all(promises);
}

编辑:

如果没有循环,那么你可以这样做:

return function(dispatch){
    return loadStorySnippet(...your arguments here, dispatch));
}