反应摩卡测试 props.history

React mocha testing props.history

我正在尝试使用 mocha 和 nock 测试一个函数,但出现错误:无法读取数据

处未定义的 属性 '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)
      })
  });
});

感谢您的帮助

registerUser 的问题在于它没有 return 承诺,这使得测试更加复杂。

应该是:

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

history.push 应该是存根:

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

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