我使用 Vite、React、Redux、Redux-Tool-Kit 和 Javascript 构建了一个应用程序,还涉及路由和 Vitest 进行测试。
我必须构建
useNavigate
钩子的模拟,但我无法使其工作。这就是我构建的:
import React from 'react';
import { renderWithProviders } from '../../../../tests_setup/test-utils';
import { screen, fireEvent } from '@testing-library/dom';
import { useNavigate } from 'react-router-dom';
import SearchInput from '../SearchInput';
import {
resetSearch,
updateSearchterm,
getData
} from '../../../features/data/dataSlice';
// Mock the useNavigate function from react-router-dom
const mockUseNavigate = vi.fn();
vi.mock('react-router-dom', async () => {
const nav = await vi.importActual<typeof import("react-router-dom")>(
"react-router-dom"
);
return {
...nav,
useNavigate: () => mockUseNavigate,
};
});
这是我的 test-utils.jsx 文件:
import React from 'react'
import { render } from '@testing-library/react'
import { Provider } from 'react-redux'
import { BrowserRouter as Router } from 'react-router-dom';
import { setupStore } from '../src/app/store'
export function renderWithProviders(
ui,
{
preloadedState = {},
// Automatically create a store instance if no store was passed in
store = setupStore(preloadedState),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
return (
<Provider store={store}>
<Router>
{children}
</Router>
</Provider>
)
}
return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) }
};
我从 Vitest 收到以下错误消息:
错误:[vitest] 上未定义“BrowserRouter”导出 “react-router-dom”模拟。您是否忘记从“vi.mock”返回它? 如果您需要部分模拟模块,可以使用“importOriginal” 里面的帮手:
vi.mock("react-router-dom", async (importOriginal) => { const 实际 = 等待 importOriginal() 返回 { ...实际的, // 你的模拟方法 } })
❯包装器tests_setup/test-utils.jsx:30:14 28| 返回 ( 29| 30| | ^ 31| {孩子们} 32| ❯ renderWithHooks node_modules/react-dom/cjs/react-dom.development.js:15486:18 ❯ 挂载不确定组件 node_modules/react-dom/cjs/react-dom.development.js:20103:13 ❯ 开始工作node_modules/react-dom/cjs/react-dom.development.js:21626:16 ❯开始工作$1 node_modules/react-dom/cjs/react-dom.development.js:27465:14 ❯ 执行工作单元 node_modules/react-dom/cjs/react-dom.development.js:26599:12 ❯ 工作循环同步 node_modules/react-dom/cjs/react-dom.development.js:26505:5 ❯ 渲染根同步 node_modules/react-dom/cjs/react-dom.development.js:26473:7
我找不到解决方案。
有人可以帮忙吗?整个测试主题对我来说仍然很困惑,所以我也很高兴得到一些解释以更好地理解。
相反:
useNavigate: () => mockUseNavigate
试试这个:
useNavigate: mockUseNavigate
或
useNavigate: vi.fn().mockReturnValue(mockUseNavigate)