【问题标题】:Enzyme & React router: How to shallow render a component with useHistoryEnzyme & React 路由器:如何使用 useHistory 对组件进行浅层渲染
【发布时间】:2020-04-20 12:29:29
【问题描述】:

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

组件正在使用来自react-router-domuseHistory

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% 确定,因为我无法从 enzymereact-router 的文档中找到 shallow 是否与 useHistory 兼容。

shallow 可以与useHistory 一起使用吗?任何建议将不胜感激。

【问题讨论】:

    标签: reactjs react-router react-hooks enzyme


    【解决方案1】:

    来自docs

    注意:为了正确地模拟,Jest 需要 jest.mock('moduleName') 来 与 require/import 语句在同一范围内。

    因此,不要在 beforeEach 中模拟 react-router-dom - 尝试将其置于顶级范围:

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

    【讨论】:

      猜你喜欢
      • 2016-12-18
      • 2017-03-11
      • 1970-01-01
      • 2016-10-29
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 2021-04-23
      • 1970-01-01
      相关资源
      最近更新 更多