I'm trying to test a function with mocha and nock, but got an error : Cannot read property 'data' of undefined at data
Here is my code
Methode to test:
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
})
);
};
Test:
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)
})
});
});
Thanks for your help
The problem with registerUser
is that it doesn't return a promise, this makes testing more complicated.
It should be:
export const registerUser = (userData, history) => dispatch => {
return axios...
};
history.push
should be a stub:
const history = { push: sinon.stub() };
return registerUser(userData, history)(dispatchSpy)...
Then it can be tested that it was called with correct argument.