Ad

Testing Navigation In React With MemoryRouter After A Button Click (jest, Enzyme)

- 1 answer

So, I'm trying to test using MemoryRouter that if I click a button that is supposed to take me to a new Route, it does actually open that route.

So 'ConversationView' is the react component inside Conversations. I- want to be able to test that when I click on the button that's located inside 'Conversations', I would be able to reach the new route 'ConversationsView' and find the 'h2' tag inside it.

This is my code:

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

What am I doing wrong? How should I be testing such a scenario?

P.S. i'm injecting a MobX store to conversations. but i did mock the store, so there is no extra async work.

Ad

Answer

Try to change expact() result:

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

Or you can try to setProps to wrapper like this:

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);
Ad
source: stackoverflow.com
Ad