【问题标题】:React mocha testing props.historyReact mocha 测试 props.history
【发布时间】:2019-02-26 19:06:57
【问题描述】:

我正在尝试使用 mocha 和 nock 测试函数,但出现错误:Cannot read property 'data' of undefined at data

这是我的代码

测试方法:

export const registerUser = (userData, history) => dispatch => {
  axios
    .post("/api/v3/user", userData)
    .then( res => {      
      history.push("/login")
      return res;
    }) 
.catch(err =>
  dispatch({
    type: GET_ERRORS,
    payload: err.response.data
  })
);
};

测试:

describe('Post registerUser', () => {    
beforeEach(() => {
  nock('http://localhost')
    .post('/api/v3/user', userData )
    .reply(200, registerResponseValide);
});

it('Register valide', () => {
    const dispatchSpy = sinon.spy();
     return registerUser(userData, history)(dispatchSpy)
      .then(response => {
        //expect an object back
        expect(typeof response).to.equal('object');
        expect(response.data.id).to.equal(registerResponseValide().id)
      })
  });
});

感谢您的帮助

【问题讨论】:

  • 我知道问题出在“历史”上,但不知道如何解决。

标签: reactjs unit-testing mocha.js nock


【解决方案1】:

registerUser 的问题在于它不返回一个承诺,这使得测试更加复杂。

应该是:

export const registerUser = (userData, history) => dispatch => {
  return axios...
};

history.push 应该是一个存根:

const history = { push: sinon.stub() };
return registerUser(userData, history)(dispatchSpy)...

然后可以测试它是用正确的参数调用的。

【讨论】:

  • 工作得很好,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多