0

Try to Make a test sign up, I got this: FAIL tests/signUp.test.js (6.256 s) Test signUp × Renders the SignIn component (181 ms)

● Test signUp › Renders the SignIn component

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

  21 |
  22 |   useEffect(() => {
> 23 |     if (!localStorageUser && !_.includes(withoutUserRouters, Router.pathname)) {
     |                                                                     ^
  24 |       Router.push(routers.signin);
  25 |     }
  26 |     setUser(localStorageUser);

  at getRouter (node_modules/next/client/router.ts:122:11)
  at Object.pathname (node_modules/next/client/router.ts:84:22)
  at context/AuthContext.js:23:69

This is The test file code:

import {fireEvent, render} from '@testing-library/react';
import '@testing-library/jest-dom';
import SignUp from '../pages/signUp';
import {AuthProvider} from '../context/AuthContext';
import {UIProvider} from '../context/UIContext';
import {SnackbarProvider} from 'notistack';

const useRouter = jest.spyOn(require('next/router'), 'useRouter');
useRouter.mockImplementation(() => ({
  pathname: '/',
}));

describe('Test signUp', () => {
  it('Renders the SignIn component', () => {
    const {getByText} = render(
      <SnackbarProvider>
        <AuthProvider>
          <UIProvider>
            <SignUp />
          </UIProvider>
        </AuthProvider>
      </SnackbarProvider>,
    );

    const button = getByText(/Sign Up/i);
    expect(button).toBeInTheDocument();
    fireEvent.click(button);
  });
});

at context/AuthContext.js Router imported like so:

import Router from 'next/router';

and then There is a useEffect like so:

  useEffect(() => {
    if (!localStorageUser && !_.includes(withoutUserRouters, Router.pathname)) {
      Router.push(routers.signin);
    }
    setUser(localStorageUser);
  }, [localStorageUser]);

Why is the mock for Router not take place?

A.B
  • 33
  • 5
  • You should add router provider – Konrad Jun 15 '23 at 12:35
  • I don't think your mocking the router correctly, please see this post https://stackoverflow.com/questions/69125633/mocking-nextjs-router-events-with-jest – Jay Jun 15 '23 at 13:48
  • I realized that on the file context/AuthContext.js There was not good practice of the import (and useEffct). The correct way of import is: import {useRouter} from 'next/router'. Have a look at https://stackoverflow.com/questions/64325145/import-router-from-next-router-is-it-ok – A.B Jun 20 '23 at 16:33

0 Answers0