2017-02-27 33 views
0

我正在爲Karma for react/redux編寫一些測試,我似乎無法修復這個bug。每次運行測試時,它都會執行該操作,將正確的值發送給reducer,但我似乎總是得到未定義的響應返回值。我們的控制檯登錄所有的值,直到更新的狀態,但是一旦該行執行:Karma在redux中測試undefined諾言

dispatch(duck.addLabRequest(newLab.toJS())).then(() => { 

我們得到的未定義一個。然後。這可能是什麼原因?

錯誤

PhantomJS 2.1.1 (Mac OS X 0.0.0) creating a new lab sends the body of the form in the request FAILED 
     undefined is not an object (evaluating 'promise.then') 

測試

describe('creating a new lab',() => { 
    let promise; 
    beforeEach(() => { 
    let mockAdapter = new MockAdapter(axios); 
    mockAdapter.onPost(labsURL).reply(201, { 
     lab: newLabWithID, 
     message: "Lab created successfully" 
    }); 
    dispatch(duck.addLabRequest(newLab.toJS())).then(() => { 
     expect(1).to.equal(2); 
    }) 
    }) 
}) 

行動

export function addLabRequest(lab) { 
    console.log("lab is: ") 
    console.log(JSON.stringify(lab)); 
    return (dispatch) => { 
    axios.post(`${API_URL}/Labs`, lab, { 
     headers: {'Content-Type': 'application/json'} 
    }) 
     .then((resData) => { 
     console.log("WE GOT HERE"); 
     console.log(JSON.stringify(resData)) 
     dispatch(addLab(resData)) 
     }) 
     .catch((err) => { 
     console.log(err.response.data.message); 
     }); 
    } 
} 

。 。 。

減速

case ADD_LAB: 

    console.log("ADDING LAB"); 
    console.log(JSON.stringify(action.payload)); 
    return state.update(
    'labs', 
    (labs) => labs.push(Immutable.fromJS(action.payload)) 
); 
+0

我想你也必須也返回'dispatcher'裏面:'回報axios.post(..)',是一個很好的做法還要返回'then((resData)...)'內的最後一個'dispatch'。 – caisah

+1

@caisah好吧,現在這個工作!發佈一個答案,我會接受它。 –

回答

0

您應該返回調度裏面。這也是一個很好的做法,在承諾返回最後調度:

export function addLabRequest(lab) { 
    return (dispatch) => { 
    return axios.post(`${API_URL}/Labs`, lab, { 
     headers: {'Content-Type': 'application/json'} 
    }) 
     .then((resData) => { 
     return dispatch(addLab(resData)); 
     }) 
     .catch((err) => { 
     console.log(err.response.data.message); 
     }); 
    } 
}