【问题标题】:Test if component is rendered for the specific route测试是否为特定路由呈现组件
【发布时间】:2019-10-01 17:31:14
【问题描述】:

我有一个这样的组件:

const App = () =>
    <BrowserRouter basename={basePath}>
        <div>
            <Header/>
            <Switch>
                <Route path="/" exact component={Dashboard}/>
                <Route path="/contact" component={ContactForm}/>
                <Route path="*" component={Dashboard} />
            </Switch>
        </div>
    </BrowserRouter>;

在我的测试中,我想检查“/contact”路由,App 确实会呈现 ContactForm 组件。我该怎么做?

如果我尝试:

const wrapper = mount(
   <MemoryRouter initialEntries={[ '/contact' ]}>
      <App/>
   </MemoryRouter>
);

但这种方式包装器也呈现仪表板所以expect(wrapper.find(ContactForm)).toHaveLength(1); 不通过。

我应该如何正确检查?


更新

这就是我现在测试它的方式:

    const wrapper = mount(
        <MemoryRouter initialEntries={[ '/' ]}>
            <App/>
        </MemoryRouter>
    );
    wrapper.find("nav").find(Link).simulate("click", { button: 0 });
    expect(wrapper.find(ContactForm)).toHaveLength(1);

所以我必须从'/'路由开始,然后模拟点击链接,然后它就可以工作了。

【问题讨论】:

    标签: reactjs jestjs enzyme react-router-v4


    【解决方案1】:

    &lt;MemoryRouter initialEntries={[ '/contact' ]}&gt;

    这应该很好用...检查 App 组件中 props.location 的值是什么 可能是BrowserRouter改变了位置

    【讨论】:

      猜你喜欢
      • 2020-12-11
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多