在我要测试的组件中,我使用了 useLocation
钩子。
在我有的组件中:
function Test() {
const history = useHistory();
const location = useLocation();
const query = new URLSearchParams(location.search).get('value');
return <div > Welcome < /div>
}
为了测试组件,我写了这个测试:
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();
});
})
尝试这个我得到 TypeError: (0 , _reactRouterDom.useLocation) is not a function
。为什么我会收到这个错误?如何正确编写测试以避免错误?
答案 0 :(得分:0)
你最好不要模拟 react-reouter-dom
和 useLocation
钩子的实现。相反,您应该使用 MemoryRouter 用 initialEntries 包装您的组件进行测试:
历史堆栈中的位置数组。这些可能是带有 { pathname, search, hash, state } 或简单字符串 URL 的完整位置对象。
例如
index.tsx
:
import React from 'react';
import { useLocation } from 'react-router-dom';
export function Test() {
const location = useLocation();
const query = new URLSearchParams(location.search).get('value');
console.log('query: ', query);
return <div> Welcome </div>;
}
index.test.tsx
:
import { render } from '@testing-library/react';
import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { Test } from './';
describe('68248240', () => {
it('should pass', () => {
render(
<MemoryRouter initialEntries={[{ pathname: '/', search: '?value=teresa_teng' }]}>
<Test />
</MemoryRouter>
);
});
});
结果:
PASS examples/68248240/index.test.tsx (10.807 s)
68248240
✓ should pass (34 ms)
console.log
query: teresa_teng
at Test (examples/68248240/index.tsx:7:11)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 11.903 s