0
我有一个问题,在reactjs中测试异步操作。 这里是我的代码:我得到TypeError:当我尝试测试异步操作时,无法读取未定义的属性'then'
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
任何想法如何,我可以解决这个问题?
非常感谢。一个问题,如果tehre不适合像这样的循环:loadStorySnippet(channel,snippetsLink [i],(i + 1),dispatch);我应该怎么包装这个承诺? –
'loadStorySnippet'返回一个承诺,因为它追溯到axios,所以你只需'返回loadStorySnippet(...)'。 –
所以你的意思是这样的:return loadStorySnippet(channel,snippetsLink [i],(i + 1),dispatch); ? –