我的 React 组件应该根据当前位置对状态进行一些更改。
有自定义钩子(Hook),在组件加载时调用。
在 Hook 中检查 useLocation().pathname
以及 switch/case 中的结果是否正确更改。
这可以在一个文件/描述中进行 Jest 测试吗?
我尝试了 jest.mock
useLocation
但我无法在 Jest describe...
这是模拟,目前不在描述范围内 - 这有效,但不能在测试之间更改:
const mockUseLocation = () => {
jest.mock('react-router-dom', () => ({
useLocation: jest.fn().mockReturnValue({
pathname: '/val1'
})
}))
};
如何测试所有 switch/case 分支?
switch (pathname) {
case 'val1':
return 100;
case 'val2':
return 200;
...
...
}
最佳答案
为了摆脱@skyboyer 的回答,我使用 renderHook
使它运行良好
第一个参数是你要测试的钩子(Hook),第二个参数是我包装的包装器 <MemoryRouter>
, <Route>
周围children
Prop 。
// test.js
import React, { FC } from 'react';
import { MemoryRouter, Route } from 'react-router-dom';
import { renderHook } from '@testing-library/react-hooks';
it('returns value from url query', () => {
const wrapper: FC = ({ children }) => (
<MemoryRouter initialEntries={[`/?user=authorized`]}>
<Route path="*" />
{children}
</MemoryRouter>
);
const { result } = renderHook(() => useLocation(), { wrapper });
expect(result.current).toBe('authorized');
});
关于jestjs - 如何为每个测试模拟不同的 useLocation 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61441886/