The test.tsx file encountered an error as the Router of Next/Router was not defined

CustomLeftSidebar.tsx Component


import { usePathname, useRouter } from 'next/navigation';

interface CustomLeftSidebarProps {
  customLeftSidebarData: InnerPathItem;
  customLeftSidebarDataIndex: number;
}

export const CustomLeftSidebarItem = (props: CustomLeftSidebarProps) => {
  const pathName = usePathname();
  const router = useRouter();

 return (
    <li
      className={`hover:bg-[rgb(0,0,0,0.18)] w-[14.625rem] h-[2.813rem] hover:rounded-xl flex items-center p-3 cursor-pointer
         ${pathName === props.customLeftSidebarData.path && `rounded-xl bg-[rgb(0,0,0,0.18)]`} mb-1 nav_li_item`}
      onClick={() => {
        router.push(props.customLeftSidebarData.path);
      }}
      key={`${props.customLeftSidebarData.label}${props.customLeftSidebarDataIndex}`}
      data-testid="custom-li-item"
    >
      {renderIcon(
        pathName === props.customLeftSidebarData.path,
        props.customLeftSidebarData.label,
      )}
      <div
        className={`p-2 text-sm ${pathName === props.customLeftSidebarData.path && 'font-bold'} text-white`}
      >
        {props.customLeftSidebarData.label}
      </div>
    </li>
  );
};

CustomLeftSidebar.spec.tsx Testing File


import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { NextRouter, useRouter } from 'next/router';

import { CustomLeftSideBar } from './CustomLeftSidebar';
import { customLeftSidebarItems } from './CustomLeftSidebarItems';

jest.mock('next/router', () => ({
  useRouter: jest.fn(),
  NextRouter: jest.fn(),
}));

jest.mock('next/navigation', () => ({
  useRouter() {
    return {
      route: '/Orders',
      pathname: '',
      query: '',
      asPath: '',
      push: jest.fn(),
      events: {
        on: jest.fn(),
        off: jest.fn(),
      },
      beforePopState: jest.fn(() => null),
      prefetch: jest.fn(() => null),
    };
  },
  usePathname() {
    return '';
  },
}));
describe('CustomLeftSideBar', () => {
  describe('Click event on Sidebar', () => {
    const mockPush = jest.fn();

    beforeEach(() => {
      const router=useRouter();
       console.log(router);
      (useRouter as jest.Mock).mockReturnValue({
        push: mockPush,
        pathname: '/',
      } as Partial<NextRouter>);
    });

    afterEach(() => {
      jest.clearAllMocks();
    });

    it('should navigate to Orders page on click', () => {
      const { getByText } = render(
        <CustomLeftSideBar customLeftSideBarPathItems={customLeftSidebarItems} />,
      );

      // Simulate click on the 'Orders' list item
      const liElement = getByText('Orders').closest('li')!;
      fireEvent.click(liElement);

      // Assert that router.push was called with the correct path
      expect(mockPush).toHaveBeenCalledWith('/Orders');
    });
  });
});

I created a custom Left sidebar component containing all the routes. My goal is to locate the "Orders" label in the list and click on it. Although the list item is clicked, I encounter an issue where expect(mockPush).toHaveBeenCalledWith('/Orders'); shows mockPush as undefined. Additionally, when attempting to print the router in beforeEach, it also appears to be undefined.

Answer №1

Instead of importing useRouter from next/router, I mistakenly imported it from next/navigation. This caused issues as the router was undefined and the push method could not be called.

import { useRouter } from 'next/navigation';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Starting Unit Testing in Django: Comprehensive Guide to Initializing Database

As I delve into Test Driven Development with Django, a hurdle I encounter is the need to populate the database with various data before running tests. This includes creating users, departments, and assigning permissions. Initially, I attempted using fixtur ...

Exploring Next JS v13: Implementing font-weight variation from Google Fonts with the help of @next/font

Since the release of Next JS v13, utilizing @next/font has been crucial for optimizing performance. Previously, I would include Google fonts using the CDN @import in my global CSS file. /* path: ./styles/global.css */ @import url("https://fonts.google ...

Transforming a Java calendar date into a JavaScript date by utilizing the getTimezoneOffset() method of the new Date object

I've been working with a calendar data that is sent to the server, which includes the following fields: export interface CalendarDate{ dayOfMonth: number; hourOfDay: number; minute: number; month: number; second: number; year: ...

Error in Next.js: The element type is not valid. Please make sure it is either a string (for built-in components) or a class/function (for composite components) and not undefined

I've encountered an issue while working on my Next.js project where I am trying to import the Layout component into my _app.js file. The error message I received is as follows: Error: Element type is invalid: expected a string (for built-in componen ...

Is there a way to customize the hover style of Material UI Select or Menu MenuItem using the theme?

The theme I designed import { createMuiTheme } from 'material-ui/styles'; export const MyTheme = createMuiTheme({ palette: { primary: { light: '#757ce8', main: '#3f50 ...

Restrict the scope of 'unknown' to an object containing only a string-field without resorting to 'any'

Currently, I am working on validating the data that is being received by my application. To illustrate, consider the following scenario: function extractField(data: unknown): string { if (typeof data !== 'object') { throw new Error(& ...

Mapping JSON to interface in Angular 7: A step-by-step guide

I am currently working with angular7 and I have a requirement to map a json object to my interface. My goal is to create a function that can accurately map the fields of the json object to the corresponding properties in the interface. Additionally, if the ...

Tips for extracting the decimal portion of a floating point number in TypeScript

Is there a way to retrieve the number that comes after the decimal point in a float number using TypeScript? For example, in the number 2.3, I would like to obtain a return of 3. ...

Receive the traits of a React component

Hey there, I'm currently working with typescript and react. I am trying to create a base class that multiple components can inherit from. import * as React from "react"; interface IBaseProps { title: string; } class Base<P extends IBaseProps ...

Fetch colors from an API to dynamically update the colors in tailwind.config.ts using Next.js

When I decided to incorporate SEO into my React project, I opted for Next.js. However, I encountered an issue when trying to load colors from the backend to be used in tailwind.config.ts. Does anyone know how to accomplish this with Next.js? ...

Can child components forward specific events to their parent component?

I created a basic component that triggers events whenever a button is clicked. InnerComponent.vue <template> <v-btn @click="emit('something-happened')">Click me</v-btn> </template> <script setup lang=" ...

Is there a way for me to add a clickable link within a tooltip?

In my title, I want to insert a clickable link like 'Link' or 'a'. The title is ready for any string you input. <MaterialSwitch title={CLICKABLE STRING HERE} /> ...

When the key property is utilized, the state in react useState is automatically updated; however, for updating without it, the useEffect or a

I am working on a component that looks like this: import React, { useState } from "react"; import { FormControl, TextField } from "@material-ui/core"; interface IProps { text?: string; id: number; onValueChange: (text: stri ...

Exclude promises from a type in TypeScript

Here is my TypeScript snippet: async function get_string(){ return "hello" } var the_string = get_string() In the code, the type of the_string is Promise<string> I am interested in removing the Promise from the type of the_string and m ...

What is the method to determine the size of an array of objects where each object contains its own internal array?

Here is the data that I have: var a=[ { name: "time", Details:[ {value:"month",checked:true,id:1} ] }, { name: "product", Details:[ {value: ...

Guide to importing a Swagger model barrel file into a Typescript file (Angular)

Our team is currently using Swagger to automatically generate our API models and we are looking for a more convenient way to import them into our project. Currently, we are importing them like this: tsconfig.ts "paths": { "apimodel/*": ["frontend/swagg ...

What is the process for including custom headers in a Next.js application?

I am looking to include an X-Robots-Tag in order to prevent search engines from indexing my website. I found a method to do this in the Vercel Docs The challenge I am currently facing is how to inject this alongside the existing configuration in my next.c ...

Matching multiline input with RegExp and grouping matches from consecutive lines

Imagine having a text file with the following content: AAAA k1="123" k2="456" several lines of other stuff AAAA k1="789" k2="101" AAAA k1="121" k2="141" The objective is to extract the values of k1 and k2 while keeping them grouped together. For instance ...

Utilizing Next Js app routing, react hook forms, react dropzone, and route handlers to facilitate the upload of various types of data such as text and

For my upcoming project, I am looking to enable authenticated users on the Next 13 web app to upload product data. This data will consist of various strings, numbers, a single featured image, and an array of product images. The form itself is a client comp ...

const error = new TypeError(`${calculateRelativePath(cwd, fileName)}: Skipping emission of file`);

Hey there! I have a typescript code snippet that looks like this: import { getConnection } from "typeorm"; import { GraphQLClient } from "graphql-request"; import got from "got"; import database from "./utils/database&quo ...