Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Router.push with Jest/React

Im still new to unit tests and im struggling to understand how i could test/mock a push from a router,

<Tab label="Members" alt="Members" onClick={() => Router.push('/members')}/>

the above line is what i need to test but how could i? would i create a fake end point and then test the onClick?

like image 206
Broken Mind Avatar asked Mar 03 '26 19:03

Broken Mind


1 Answers

The easiest thing would be to mock the router like this

import Router from 'next/router'
jest.mock('next/router', ()=> ({push: jest.fn()}))

after simulate the click on Tab you can check for the call like this

expect(Router.push).toHaveBeenCalledWith('/members')
like image 63
Andreas Köberle Avatar answered Mar 05 '26 08:03

Andreas Köberle



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!