单击按钮后测试导航与 MemoryRouter 的反应(开玩笑,酶)

Testing navigation in react with MemoryRouter after a button click (jest, enzyme)

所以,我正在尝试使用 MemoryRouter 进行测试,如果我单击一个应该带我到新 Route[=23= 的按钮],它确实打开了那条路线。

所以 'ConversationView' 是 Conversations 中的 React 组件。我- 希望能够测试当我单击位于 'Conversations' 内的按钮时,我将能够到达新路线 'ConversationsView' 并在其中找到 '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);

我做错了什么?我应该如何测试这种情况?

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

尝试更改 expact() 结果:

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

或者您可以像这样尝试将 Props 设置为包装器:

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);