Reputation: 5539
I want to test the page get redirected after click on div, but I dont know how, this is my code. Thank you so much
<div className="bellTest">
<NextLink href="/notifications">
<Bell />
</NextLink>
</div>
test.tsx
jest.mock('next/link', () => {
return ({ children }) => {
return children;
};
});
describe('Test of <HeaderContainer>', () => {
test('Test the page redirect after click', async done => {
const wrapper = mount( <HeaderComponent /> );
await wrapper
.find('.bellTest')
.at(0)
.simulate('click');
// expect the page getting redirect
});
});
Upvotes: 7
Views: 12271
Reputation: 35553
Instead of mocking next/link
you can register a spy on router events, and check if it was called.
The test will look like this:
import Router from 'next/router';
describe('Test of <HeaderContainer>', () => {
const spies: any = {};
beforeEach(() => {
spies.routerChangeStart = jest.fn();
Router.events.on('routeChangeStart', spies.routerChangeStart);
});
afterEach(() => {
Router.events.off('routeChangeStart', spies.routerChangeStart);
});
test('Test the page redirect after click', async done => {
const wrapper = mount(<HeaderComponent />);
await wrapper
.find('.bellTest')
.at(0)
.simulate('click');
expect(spies.routerChangeStart).toHaveBeenCalledWith('expect-url-here');
});
});
Upvotes: 3