Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 970
Hadi Abu Avatar asked Nov 23 '25 19:11

Hadi Abu


1 Answers

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);
like image 178
James Delaney Avatar answered Nov 26 '25 11:11

James Delaney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!