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); ? –