首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在单元测试中使用连接反应路由器的推送

如何在单元测试中使用连接反应路由器的推送
EN

Stack Overflow用户
提问于 2020-06-10 23:17:40
回答 1查看 348关注 0票数 1

我希望在测试期间通过connected-react-router更新存储在我的redux存储中的URL,因为我的一些逻辑依赖于此。当我dispatch一个push时,操作会被记录下来(我可以使用记录器中间件来验证),但是实际的状态并没有改变。

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

代码语言:javascript
复制
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/');
    });
});

有没有人知道为什么它不能像我预期的那样工作?

相关包:

代码语言:javascript
复制
    "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",
EN

回答 1

Stack Overflow用户

发布于 2021-05-25 15:45:07

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

代码语言:javascript
复制
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>
      );
  });
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62307100

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档