Search code examples
reactjsreact-reduxaxiosredux-thunkreactjs-testutils

I get TypeError: Cannot read property 'then' of undefined when I try to test async action


I have a problem testing my async action in reactjs. Here is my code:

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){

    });
 }

So my asnc call is in a function which is not exported and there is a function calling this asnc function in a for loop.

Now here is my test:

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);
    })
})

Now the problem is when run the test I get:

TypeError: Cannot read property 'then' of undefined

Any idea how I can fix this?


Solution

  • The thunk function returned by fillStoryBoard does not return a promise, so you can't .then off of it.

    Try something like this:

    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);
    }
    

    EDIT:

    If there is no loop, then you could just do this:

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