【问题标题】:Karma tests undefined promise in reduxKarma 在 redux 中测试未定义的 Promise
【发布时间】:2017-07-18 05:49:27
【问题描述】:

我正在 Karma 中为 react/redux 编写一些测试,但我似乎无法修复这个错误。每次运行测试时,它都会运行动作,将正确的值发送给减速器,但我似乎总是得到未定义的响应返回。我们控制台记录了所有值,直到更新状态,但是一旦执行此行:

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

【问题讨论】:

  • 我认为您还必须在 dispatcher:return axios.post(..) 内返回,并且在 then((resData)...) 内也返回最后一个 dispatch 是一个好习惯。
  • @caisah 好的,现在可以了!发布答案,我会接受。

标签: javascript testing redux karma-runner axios


【解决方案1】:

您应该在调度程序内部返回。在 promise 中返回最后一个 dispatch 也是一个好习惯:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 2017-06-21
    • 2020-04-13
    • 2019-12-10
    相关资源
    最近更新 更多