路由器.预取不是一个功能,无法在react测试库中检查提交功能



这是一个组件的测试代码,我需要检查表单提交函数是否被调用。

import React from 'react'
import { render, screen, fireEvent, debug } 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' })); // or which pathname you want to test
let companies = [
{
"name": "Fake Company Express",
"phone": "9876543210",
"email": "test@company.com",
"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() 
})
})

和添加组件代码是:

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>
}

我使用react钩子形式,得到错误作为

TypeError:路由器。预取不是一个功能

每当我需要使用"next/router"我总是这样调用useRouter并把它赋值给一个变量:

import { useRouter } from "next/router"
const router = useRouter()

也许这有帮助