You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest测试报错TypeError: Cannot read property 'then' of undefined求解决

解决 TypeError: Cannot read property 'then' of undefined 问题

我来帮你拆解这个问题的根源和修复方案:

错误核心原因

你遇到的这个报错,本质是你的getContacts action creator没有返回Promise。Redux Thunk允许你返回一个函数,但如果想在测试里用.then()链式调用dispatch的结果,这个thunk函数必须返回一个Promise(也就是axios请求的Promise链),否则store.dispatch(actions.getContacts())会返回undefined,自然没法调用.then()方法。

第一步:修复Action Creator

修改contact-actions.js,给axios请求加上return,把Promise返回出去:

export function getContacts() {
  return function(dispatch) {
    dispatch({type: 'GET_CONTACTS_PENDING'})
    // 关键:返回axios请求的Promise链
    return axios.get('http://127.0.0.1:8000/api/contacts', { })
    .then((response) => {
      dispatch({type: 'GET_CONTACTS', payload: response.data})
      dispatch(hideLoading())
    })
    .catch((error) => {
      dispatch({type: 'CONTACT_ERROR', payload: error})
      // 可选:把错误抛出,方便测试捕获异常场景
      return Promise.reject(error);
    })
  }
}

第二步:修正测试用例的细节问题

除了action的问题,你的测试代码还有两处需要调整,才能确保断言通过:

  1. Expected Actions遗漏了Pending状态:你的action首先dispatch了GET_CONTACTS_PENDING,但测试里的expectedActions没包含这个,会导致断言失败。
  2. 数据结构不匹配:你用nock返回的是body.contacts,但action里用的是response.data(也就是nock返回的整个body对象),所以expectedActions的payload要对应这个结构。

修改后的测试代码片段:

const expectedActions = [
  { type: types.GET_CONTACTS_PENDING }, // 补上Pending状态的action
  { 
    type: types.GET_CONTACTS,
    payload: {
      contacts: [{
        first_name: 'shadow',
        last_name: 'madow',
        phone: 5566,
        email: 'shadow@yahoo.com'
      }]
    }
  }
];

return store.dispatch(actions.getContacts()).then(() => {
  expect(store.getActions()).toEqual(expectedActions);
});

另外,你的测试里同时导入了moxios、MockAdapter和nock三种axios mock工具,建议只保留一种(比如nock),避免工具之间的冲突,清理掉冗余的导入即可。

内容的提问来源于stack exchange,提问作者user-9725874

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:27:57