'How to use connected-react-router's push within unit tests
I want to update the URL that is stored in my redux store by connected-react-router during testing, because some of my logic depends on that. When I dispatch a push, the actions gets logged (I was able to verify that using a logger middleware), but the actual state does not change.
I have this code to reproduce the specific issue:
import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import thunkMiddleware from 'redux-thunk';
import { connectRouter, push, routerMiddleware } from 'connected-react-router';
import { createMemoryHistory } from 'history';
const history = createMemoryHistory();
export function createReduxStore() {
return createStore(
combineReducers({
router: connectRouter(history),
}),
{},
compose(
applyMiddleware(
routerMiddleware(history),
thunkMiddleware,
)
)
);
}
describe('router', () => {
it('gets the correct data in URL', () => {
const store = createReduxStore();
expect(store.getState().router.location.pathname).toEqual('/');
store.dispatch(push('/kg/firefox/resource/?string=42'));
// This fails, `pathname` is still "/"
expect(store.getState().router.location.pathname).toEqual('/kg/firefox/resource/');
});
});
Does anyone have any idea why this is not working as I expect it to?
Relevant packages:
"react": "16.12.0",
"connected-react-router": "6.8.0",
"react-redux": "7.1.3",
"react-router": "5.2.0",
"react-router-dom": "5.2.0",
"react-scripts": "3.3.0",
"redux": "4.0.5",
"redux-logger": "3.0.6",
"redux-thunk": "2.3.0",
Solution 1:[1]
I found the solution in connected-react-router tests : https://github.com/supasate/connected-react-router/blob/master/test/ConnectedRouter.test.js
the component ConnectedRouter subscribe to the store when he's mounted : https://github.com/supasate/connected-react-router/blob/master/src/ConnectedRouter.js
You need to mount the component with enzime as they do in their tests
import { configure, mount } from 'enzyme';
configure({ adapter: new Adapter() });
beforeEach(() => {
const history = createMemoryHistory();
const store = createReduxStore(history);
//init connected-react-router to connect history and store
mount(
<Provider store={store}>
<ConnectedRouter history={history}>
<Route path="/" render={() => <div>Test</div>} />
</ConnectedRouter>
</Provider>
);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
