Karma在redux中测试未定义的承诺

时间:2017-02-27 14:50:30

标签: javascript testing redux karma-runner axios

我正在Karma中为react / redux编写一些测试,我似乎无法解决这个问题。每次运行测试时,它都将运行该操作,将正确的值发送到reducer,但我总是得到一个未定义的响应返回。我们控制台记录所有值,直到更新状态,但一旦执行此行:

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

我们得到了一个未定义的.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))
  );

1 个答案:

答案 0 :(得分: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);
      });
  }
}