1

我想在测试期间更新存储在我的redux商店中的 URL connected-react-router,因为我的一些逻辑依赖于此。当我dispatchapush时,操作会被记录(我能够使用记录器中间件来验证),但实际状态不会改变。

我有这段代码来重现特定问题:

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/');
    });
});

有谁知道为什么这不能像我期望的那样工作?

相关包:

    "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",
4

1 回答 1

-1

我在 connected-react-router 测试中找到了解决方案:您需要使用 enzime 安装组件:

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>
      );
  });
于 2021-05-25T07:45:07.160 回答