【问题标题】:Testing navigation in react with MemoryRouter after a button click (jest, enzyme)单击按钮后测试导航与 MemoryRouter 的反应(开玩笑,酶)
【发布时间】:2019-08-08 02:17:30
【问题描述】:

所以,我正在尝试使用 MemoryRouter 进行测试,如果我单击一个应该将我带到新 Route 的按钮,它实际上会打开该路由.

所以“ConversationView”是对话中的反应组件。我希望能够测试,当我单击位于“对话”内的按钮时,我将能够到达新路线“对话视图”并在其中找到“h2”标签。

这是我的代码:

const wrapper = mount(
   <MemoryRouter initialEntries={[ "/" ]}>
     <Conversations.wrappedComponent store={store}>
       <ConversationView>
       </ConversationView>
     </Conversations.wrappedComponent>
   </MemoryRouter>);

   const button = wrapper.find("button").first();
   button.simulate("click");
   expect(wrapper.find("h2")).toHaveLength(1);

我做错了什么?我应该如何测试这样的场景?

附:我正在向对话中注入 MobX 商店。但我确实模拟了商店,所以没有额外的异步工作。

【问题讨论】:

  • 你的click处理程序做异步工作吗?
  • 不,它只是应该渲染一个不同的页面。

标签: reactjs testing jestjs router enzyme


【解决方案1】:

尝试改变expact()结果:

 expect(wrapper.find("h2")).toEqual(1);

或者你可以尝试像这样设置属性来包装:

const wrapper = mount(
            // remove initialEntrie from here
            <MemoryRouter>
                <Conversations >
                    <ConversationView>
                    </ConversationView>
                </Conversations>
            </MemoryRouter>);

        // set props (initialEntries) to the component 
        wrapper.setProps({ initialEntries: '/' })

        const button = wrapper.find("button").first();
        button.simulate("click");
        expect(wrapper.find("h2")).toHaveLength(1);

【讨论】:

  • 不,这并没有真正改变任何东西。
猜你喜欢
  • 2023-03-27
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-10
  • 2015-10-27
  • 2017-01-25
  • 2021-02-26
相关资源
最近更新 更多