'Unit testing useRouter's isReady

I have a component, which takes a parameter from the url and displays it. I implemented it using useRouter's isReady property. Something like this:

import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';

export const Address: React.FC = () => {
  const [address, setAddress] = useState<string | undefined>(undefined);
  const router = useRouter();
  useEffect(() => {
    if (router.isReady) {
      setAddress(router.query?.address as string | undefined);
    }
  }, [router.isReady]);
  return <p>{address}</p>;
};

Now, I'm trying to unit test it, but the test fails and it seems that the parameter is never displayed in the component. Here is what I have:

import { render } from '@testing-library/react';
import '@testing-library/jest-dom';

const useRouter = jest.spyOn(require('next/router'), 'useRouter');

it('shows address', () => {
  let isReady = false;
  useRouter.mockImplementation(() => ({
    isReady,
    query: {address: 'abc'}
  }));
  const {getByText} = render(<Address />)
  isReady = true;

  expect(getByText('abc')).toBeInTheDocument();
});

Any ideas on how to make it work?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source