jest react-testing-library 错误符号不是函数

jest react-testing-library error symbol is not a function

大家好,我对简单测试有疑问,我尝试测试 Link 标签中有文本,导航中有 link 标签,但我看到错误符号不是函数,你能帮帮我吗?

我的测试代码:

const mockUseLocationValue = {
    pathname: "",
    search: '',
    hash: '',
    state: null
}
jest.mock('react-router', () => ({
    ...jest.requireActual("react-router") as {},
    useLocation: jest.fn().mockImplementation(() => {
        return mockUseLocationValue;
    })
}));

test("should render the home page", () => {
    render(<Header />);
    const navbar = screen.getByTestId("navbar");
    const link = screen.getByTestId("home-link");
    expect(link.innerHTML).toMatch("Home page");
    expect(navbar).toContainElement(link);
});

我的原码:

export const Header = ():JSX.Element => {
    const location = useLocation()
    const { pathname } = location
    const splitLocation = pathname.split('/')
    return (
        <HeaderBlock as='h3' block>
            <nav data-testid="navbar">
                <ul className={styles.links}>
                    <li>
                        <Link data-testid="home-link" to="/">
                            Home Page
                        </Link>
                    </li>
                </ul>
            </nav>
        </HeaderBlock>
    )
}

使用 react-testing-library 时,您可以为 render 函数指定其他选项,其中之一是 wrapper.

wrapper

Pass a React Component as the wrapper option to have it rendered around the inner element. This is most useful for creating reusable custom render functions for common data providers.

你不应该模拟你正在测试的功能。

在玩笑中创建用于测试的内存路由器。

import { MemoryRouter } from 'react-router-dom';

export const RouterWrapper = ({ children }) => (
  <MemoryRouter>{children}</MemoryRouter>
);

在测试中,导入包装器并传入选项。

import { RouterWrapper } from '../path/to/test/util';

test("should render the home page", () => {
  render(
    <Header />,
    {
      wrapper: RouterWrapper
    }
  );

  const navbar = screen.getByTestId("navbar");
  const link = screen.getByTestId("home-link");

  expect(link.innerHTML).toMatch("Home page");
  expect(navbar).toContainElement(link);
});