我在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
知道如何解决这个问题吗?
答案 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));
}