【问题标题】:Enzyme `mount` not rendering `Route` elements酶“mount”不渲染“Route”元素
【发布时间】:2018-08-29 00:24:27
【问题描述】:

我有这个简化的render() 方法:

render() {
    return (
        <React.Fragment>
            <Router>
                <div>
                    <Route path='/abc' component={Test} />
                    <Route path='/def' render={() => (
                        <div>Hello</div>
                    )} />
                </div>
            </Router>
        </React.Fragment>
    )
}

还有这个酶测试:

test('Render <Test> on /abc', () => {
    const wrapper = mount(
        <MemoryRouter initialEntries={['/abc']} >
            <App />
        </MemoryRouter>
    );
    console.log(wrapper.debug());
    expect(wrapper.find(Test)).to.have.lengthOf(1);
});

但是,mount() 不会在/abc 路由上渲染组件Test,或在/def 路由上渲染&lt;div&gt;Hello&lt;/div&gt;。

console.log(wrapper.debug()); 的输出:

  <MemoryRouter initialEntries={{...}}>
    <Router history={{...}}>
      <App>
        <BrowserRouter>
          <Router history={{...}}>
            <div>
              <Route path="/abc" component={[Function: Test]} />
              <Route path="/def" render={[Function: render]} />
            </div>
          </Router>
        </BrowserRouter>
      </App>
    </Router>
  </MemoryRouter>

如何测试该应用是否会在 /abc 路由上实际呈现 Test 组件?

【问题讨论】:

    标签: reactjs enzyme


    【解决方案1】:

    我已经设法找到了一个模拟路由器的解决方案:

    import React from 'react';
    const reactRouterDom = require('react-router-dom');
    
    // Render plain div with children
    reactRouterDom.BrowserRouter = ({children}) => <div>{children}</div>
    module.exports = reactRouterDom;
    

    【讨论】:

      猜你喜欢
      • 2018-09-25
      • 1970-01-01
      • 1970-01-01
      • 2021-04-01
      • 2018-08-07
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多