Ad
React - Redux: Testing Actions Dispatched Inside Other Actions
I'm using redux for a react app, with a thunk middleware.
I have this method:
export function login(username, password) {
return function (dispatch, getState) {
dispatch(loginRequest());
return sessionService.login(dispatch, username, password).then(redirectTo => {
dispatch(handleSuccessfulAuthentication(redirectTo));
}).catch(error => {...}
};
}
So I'm nocking the result of the service, and get the actions ok. But I want to test I'm dispatching the method handleSuccessfulAuthentication
but spying on that method does not seems to work, it always return it was not called (besides I see the action returned)
This is basically my test:
describe('WHEN logging in from sessionExpired', () => {
let action;
beforeAll(() => {
...
testHelper.getUnAuthenticatedNock()
.post(`/${endpoints.LOGIN}`, credentials)
.reply(200, {
...loginResponse
});
action = sinon.spy(sessionActions, 'handleSuccessfulAuthentication');
return store.dispatch(sessionActions.login(credentials.username, credentials.password))
}
it('Should redirect to previous visited page', () => {
console.log(action.called); // false
});
Ad
Answer
You need to call the exported function (please note we're calling handleSuccessfulAuthentication
bound to exports
):
export function login(username, password) {
return function (dispatch, getState) {
dispatch(loginRequest());
return sessionService.login(dispatch, username, password).then(redirectTo => {
dispatch(exports.handleSuccessfulAuthentication(redirectTo));
}).catch(error => {...}
};
}
And then your test:
it('Should redirect to previous visited page', () => {
console.log(action.called); // false
});
It's a weird issue where you have to call the function bound to exports. More information found here: https://github.com/facebook/jest/issues/936#issuecomment-214939935
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad