我一直在尝试使用渲染组件shallow
,该组件由提供enzyme
。
该组件正在使用useHistory
from react-router-dom
。
const baseMatch: match<{ id: string }> = { /* path, url, params */};
const location = createLocation(baseMatch.url);
describe('MyComponent', () => {
const baseProps = {
history: createMemoryHistory(),
location: createLocation(baseMatch.url),
match: baseMatch
};
beforeEach(() => {
jest.mock('react-router-dom', () => ({
useHistory: jest.fn()
}));
});
afterEach(() => { jest.clearAllMocks() });
it('renders blah blah', () => {
const wrapper = shallow(<MyComponent {...baseProps} />);
// testing MyComponent here...
});
我提到了这篇文章,并jest.mock
以同样的方式提出。
但是,这导致TypeError: Cannot read property 'history' of undefined
。
控制台说:
MyComponent › renders blah blah
TypeError: Cannot read property 'history' of undefined
24 | const MyComponent = (props: IProps) => {
25 | console.log('useHistory', useHistory);
> 26 | let history = useHistory();
奇怪的是,console.log
上面第25行中显示的实现useHistory
(换句话说,它不是未定义的)。
显然,useHistory
没有嘲笑。我怀疑这useHistory
不能被嘲笑shallow
(在上面的帖子中,海报使用mount()
)。
不过,我不是100%肯定,因为我无法找到,如果shallow
是兼容useHistory
的的文档或不enzyme
和react-router
。
是否有可能使用shallow
与useHistory
?任何建议将被认真考虑。
从文档:
注意:为了正确模拟,Jest需要jest.mock('moduleName')与require / import语句在同一范围内。
因此,不要嘲笑react-router-dom-beforeEach
尝试将其放在顶级范围内:
jest.mock('react-router-dom', () => ({
useHistory: jest.fn()
}));
const baseMatch: match<{ id: string }> = { /* path, url, params */};
const location = createLocation(baseMatch.url);
describe('MyComponent', () => {
const baseProps = {
history: createMemoryHistory(),
location: createLocation(baseMatch.url),
match: baseMatch
};
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句