在 React 测试库中测试 useLocation()

Ask*_*ing 7 javascript jestjs react-router

在我想测试的组件中,我使用useLocation钩子。在我的组件中:

function Test() {
  const history = useHistory();
  const location = useLocation();
  const query = new URLSearchParams(location.search).get('value');

  return <div > Welcome < /div>
}
Run Code Online (Sandbox Code Playgroud)

为了测试该组件,我编写了这个测试:

jest.mock('react-router-dom', () => ({
    useLocation: jest.fn().mockReturnValue({
        pathname: '',
        search: 'value',
        hash: '',
        state: null,
        key: '5nvxpbdafa',
    }),
}));

jest.mock('react-router-dom', () => ({
    useHistory: () => jest.fn().mockReturnValue({
        push: jest.fn(),
    }),
}));

describe(' page test', () => {
    test('should render', () => {
        render(<Test />);
        const title = screen.getByText(/welcome/i);

        expect(title).toBeInTheDocument();
    });
})
Run Code Online (Sandbox Code Playgroud)

尝试这个我明白了TypeError: (0 , _reactRouterDom.useLocation) is not a function。为什么我会收到此错误?如何正确编写测试以避免错误?

sli*_*wp2 32

你最好不要mockreact-reouter-dom和hook的实现useLocation。相反,您应该使用MemoryRouter用initialEntries包装您的组件以进行测试:

\n
\n

历史堆栈中的位置数组。这些可能是带有 { pathname, search, hash, state } 或简单字符串 URL 的成熟位置对象。

\n
\n

例如\n index.tsx

\n
import React from \'react\';\nimport { useLocation } from \'react-router-dom\';\n\nexport function Test() {\n  const location = useLocation();\n  const query = new URLSearchParams(location.search).get(\'value\');\n  console.log(\'query: \', query);\n\n  return <div> Welcome </div>;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

index.test.tsx

\n
import { render } from \'@testing-library/react\';\nimport React from \'react\';\nimport { MemoryRouter } from \'react-router-dom\';\nimport { Test } from \'./\';\n\ndescribe(\'68248240\', () => {\n  it(\'should pass\', () => {\n    render(\n      <MemoryRouter initialEntries={[{ pathname: \'/\', search: \'?value=teresa_teng\' }]}>\n        <Test />\n      </MemoryRouter>\n    );\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

结果:

\n
 PASS  examples/68248240/index.test.tsx (10.807 s)\n  68248240\n    \xe2\x9c\x93 should pass (34 ms)\n\n  console.log\n    query:  teresa_teng\n\n      at Test (examples/68248240/index.tsx:7:11)\n\nTest Suites: 1 passed, 1 total\nTests:       1 passed, 1 total\nSnapshots:   0 total\nTime:        11.903 s\n
Run Code Online (Sandbox Code Playgroud)\n