本文介绍了酶与React Router:如何使用useHistory浅化渲染组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图用 shallow 渲染组件,该组件由 enzyme 提供.

What I've been trying is to render a component with shallow, which is provided by enzyme.

该组件正在使用 react-router-dom 中的 useHistory .

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 以相同的方式.

I referred to this post, and put jest.mock in the same way.

但是,这会导致 TypeError:无法读取未定义的属性"history" .

控制台说:

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 的实现(换句话说,它不是未定义的).

Strangely, the console.log in line 25 above prints the implementation of useHistory (In other words, it's not undefined).

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

Clearly, useHistory isn't mocked.I suspect that useHistory can't be mocked with shallow (In the post above, the poster was using mount()).

但是,我不确定100%是因为我无法从 enzyme 文档中找到 shallow 是否与 useHistory 兼容?code>和 react-router .

However, I'm not 100% sure because I can't find if shallow is compatible with useHistory or not from the docs of enzyme and react-router.

是否可以将 shallow useHistory 一起使用?任何建议将不胜感激.

Is it possible to use shallow with useHistory? Any advice will be appreciated.

推荐答案

来自 docs a>:

因此,与其在 beforeEach 中嘲笑react-router-dom,不如在顶部作用域中尝试它:

So instead of mocking react-router-dom in beforeEach - try having it at the top scope:

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
  };

...

这篇关于酶与React Router:如何使用useHistory浅化渲染组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!