The functionality of router.prefetch is not recognized, which is causing difficulties in verifying the submit function with React Testing Library

This is a test code for evaluating the functionality of a component. I am checking whether a form submit function is triggered or not.

import React from 'react'
import { render, screen, fireEvent } from '@testing-library/react'
import '@testing-library/jest-dom'
import * as nextRouter from 'next/router'
nextRouter.useRouter = jest.fn()
nextRouter.useRouter.mockImplementation(() => ({ route: '/' }))
import Locations from '../pages/settings/locations'
import Add from '../pages/settings/locations/add'
import { act } from 'react-dom/test-utils'

describe('Add Locations', () => {
nextRouter.useRouter.mockImplementation(() => ({ route: '/settings/locations/add', pathname: '/settings/locations/add' }));
let companies = [
    {
        "name": "Fake Company Express",
        "phone": "9876543210",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8acbdabac98bbb7b5a8b9b6a1f6bbb7b5">[email protected]</a>",
        "contact": "Test",
        "address1": "Fake address1",
        "address2": "Fake address2",
        "address3": "",
        "city": "Fake City",
        "zip": "123456",
        "state": "State",
        "country": "Demo Test",
        "UUID": "9d8616dd-4689-4689-8812-a2345ccdcfc5"
    }
]

it('validate before save add location data', async () => {
        const mockAdd = jest.fn()
        const {getByLabelText, getByRole} = render(<Add data={companies} addLocation={mockAdd} />)

        const addButton = screen.getByTestId('addLocationBtn')

        await act(async () => {        

            fireEvent.change(getByRole("textbox", { name: /name/i }), {
                target: { value: "sds" }
            });
            fireEvent.input(getByRole("combobox", { name: /company/i }), {
                target: { value: "sdsd" }
            });
        })  

        await act(async () => {
          fireEvent.click(addButton);
        })
       expect(mockAdd).toHaveBeenCalled() 
  })

})

The code for the Add Component looks like this:

import { useForm } from 'react-hook-form';
export default function Add({...props}) {
   const {
     register,
     handleSubmit,
     formState: { errors },
   } = useForm();

   const addLocation = async (data) => {
        console.log(data)
   }
   
   <form className="g-3" onSubmit={handleSubmit(addLocation)} data-testid="addLocationForm">
   <div className="col-md-4 col-lg-4 col-sm-6 mb-3">
     <label htmlFor="" className="form-label">Name</label>
                                                        
     <input type="text" {...register('name', { required: true })} className="form-control" data-testid="name" placeholder="Enter Name Here" />
                                                        {errors.name && <p className="error" role="error" data-testid="name_error">Name is required.</p>}
                                                    
 </div>
 <input type="submit" className="btn btn-primary float-end" value="Save Location" data-testid="addLocationBtn" />
 </form>
}

I have encountered an error while using react hook form:

TypeError: router.prefetch is not a function

Answer №1

When it comes to using "next/router", my go-to method is importing useRouter and assigning it to a variable like so:

import { useRouter } from "next/router"

const route = useRouter()

Give this a try, it might make things easier!

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

The height of the ReactPlayer dynamically adjusts to accommodate content beyond the boundaries of the page

I have a video on my webpage that I want to take up the entire screen, but currently, users have to scroll a bit to reach the bottom, which is not ideal. This is my JavaScript: <div id="page"> <div id="video-container"> ...

The SyntaxError is triggered by the React-Native FlatList component

As a newcomer to React Native, I am facing an issue with refreshing the component to load city names stored in async storage. The error occurs when I utilize the FlatList component for the first time. The specific error message I encountered is: SyntaxE ...

Implementing the Reactjs mouse over and mouse out events within a popover element for a smooth user experience

I've been working on implementing a React Material Popover(https://material-ui.com/api/popover/) feature. It should be displayed when a user hovers over a TableRow (https://material-ui.com/api/table-row/), and hidden when the mouse moves out of the Ta ...

Exploring ways to turn off IconButton ripple effect in Material UI?

I have an AppBar that includes an IconButton. When I hover over the button, it displays an oval hover effect. I attempted to disable it by using: disableFocusRipple={true} However, this did not work as expected. Can someone provide me with a solution? h ...

Guide to updating material ui icon based on the server's feedback

In my table, there is a column labeled status. The backend returns three values for this column: "approve", "Review", and "pending". I am trying to change the icon shape based on the status value. Specifically, when the status is "approve", I want to use t ...

Troubleshooting Problem: Adjusting the hover border color for TextField in ReactJS Material UI

I'm having trouble setting the hover border color of a TextField to a theme variable. It seems that in order for the hover borderColor to work, it needs the "!important" tag. However, I am unsure of how to incorporate this into the theme variable. Th ...

Enhancing react-to-print functionality for optimal performance across various browsers and mobile platforms

Currently, I am developing a sample react-to-print resume template to be included in a larger portfolio website. While testing the page on Chrome and Edge browsers on a laptop, everything seems optimized. However, there are issues when using Firefox; the b ...

Sending pictures to Express via Multer using fetch

I am currently working on uploading images to an Express server. While I have been referencing MDN, express, react-dropzone, and multer Documentation, I am still unsure of the exact process. It seems that Multer is not recognizing the FormData object from ...

When the meta tag content "&" is used, it will be converted to "&amp;" in the final output

In my Nextjs webapp, I am utilizing Firebase to store images. The URI contains the "&" sign that is being converted to "&" inside the Head component. For instance, if I create a simple tag like this <meta property="test" content="& ...

Creation of Card Component with React Material-UI

I am facing difficulties in setting up the design for the card below. The media content is not loading and I cannot see any image on the card. Unfortunately, I am unable to share the original image due to company policies, so I have used a dummy image for ...

Utilizing the useSelect hook in Typescript to create custom types for WordPress Gutenberg, specifically targeting the core/editor

As I delve into development with WordPress and the Gutenberg editor, my goal is to incorporate TypeScript into the mix. However, I encounter a type error when trying to utilize the useSelect() hook in conjunction with an associated function from the core/e ...

How can I update the value of a Material-UI v4 textField using Redux-form?

How can I update the value of a TextField using redux-form? My current version includes: "@material-ui/core": "^4.11.0" "redux-form": "^8.3.6" Prior to implementing redux-form, I was able to update the TextFiel ...

The type "AppRouterInstance" cannot be assigned to type "nextRouter"

Within my Next.js project, a registration form is included as seen below: "use client"; import * as React from "react"; import { zodResolver } from "@hookform/resolvers/zod"; import { useForm } from "react-hook-form" ...

Tips for transferring a boolean value to a generic parameter in Java?

Looking to pass a boolean value to the Generic type in order to be utilized within a condition. This is the generic type interface OptionTypeBase { [key: string]: any; } type OptionsType<OptionType extends OptionTypeBase> = ReadonlyArray<Opt ...

Guide on creating 2 select inputs with distinct elements?

Imagine you have two select inputs called 'Favorite Fruits' and 'Least Favorite Fruits'. Both of them contain a list of 5 fruits. // The following code is an example to demonstrate the issue <select name='favoriteFruits'& ...

Navigating to different pages while passing state or props can be achieved by using the router.push method in Next.js

Previously, I was utilizing the router from 'next/router', but after checking out the documentation for version 13, it seems that I need to switch to using 'next/navigation'. However, I am unsure how to pass user data to navigate with t ...

Validate a field in a Formik form using React JS

Currently, I am utilizing Formik along with Yup for a project that is in progress. I am in the process of creating a multi-step form. The goal is to display the second step inputs when the user clicks on the next button, only if the inputs from step 1 are ...

When incorporating React-query with Next.js and utilizing hydration configuration for server-side rendering, cached results are not utilized, leading to the need to perform another fetch request

While working on my nextjs app, I decided to implement react-query with SSR/SSG and went through several tutorials. I opted for the hydration configuration over the initialData approach as it seemed more efficient. Following the instructions in the react- ...

What is the correct way to run npm and node on Windows 11? I keep encountering an error when attempting to execute npm install on my Windows system

I am encountering an error message when attempting to execute npm install or npm install nodejs-java on my Windows 11 system. Here are the versions: npm version - 9.6.1 node version - v18.15.0 Visual studio - 2017 Despite multiple attempts, I have been u ...

What could be the reason for the undefined value of my ID retrieved from the next JS router.query upon page refresh?

When using the id obtained from the next router.query to dynamically render elements, it works fine when accessing the room from next/link. However, upon refreshing the page, an error is thrown. https://i.stack.imgur.com/yEjGS.png Below is the code snipp ...