酶和反应路由器:如何使用useHistory浅化呈现组件

问题描述 投票:0回答:1

我一直在尝试用shallow渲染组件,该组件由enzyme提供。

组件正在使用useHistory中的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...
  });

我指的是this post,并以相同的方式放入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();

奇怪的是,上面第25行的console.log打印了useHistory的实现(换句话说,它不是未定义的。)>

显然,useHistory没有被嘲笑。我怀疑useHistory不能被shallow嘲笑(在上面的帖子中,发布者使用的是mount())。

但是,我不确定100%,因为从shallowuseHistory的文档中找不到enzyme是否与react-router兼容。

是否可以将shallowuseHistory一起使用?任何建议将不胜感激。

我一直在尝试用酶提供的组件变浅。该组件正在使用来自react-router-dom的useHistory。 const baseMatch:匹配= {/ * ...

reactjs react-router react-hooks enzyme
1个回答
0
投票

docs

© www.soinside.com 2019 - 2024. All rights reserved.