How do I test redirection with routeChangeStart React/Nextjs app?

Viewed 1236

I want to test the page get redirected after click on div using next/link, I write test file as below but it's not correct and show this error

No router instance found. You should only use "next/router" inside the client side of your app.

this is my code. Thank you so much for your helps

HeaderContainer.tsx

import Link from 'next/link'

<Link href="/notifications">
    <Bell className="bellTest" />
</Link>

test.tsx

import Router from 'next/router';
import { mount } from 'enzyme';

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('/notifications');
  });
});
0 Answers
Related