2017-02-27 70 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); 
     }); 
    } 
}