'Jest test case for React hook component

When I write a react hook component which import '*.png' resource like this:

import React, { useState, useEffect } from 'react';
import './topMenu.less';
import intl from 'react-intl-universal';
import { Breadcrumb } from 'antd';
import home from '@/image/project/home.png';

const TopMenu: React.FC<{}> = () => {
  const [page, setPage] = useState<string>('overview');
  const [projectName, setProjectName] = useState<string>('');

  useEffect(() => {
    let hashUrl = window.location.hash;
    let tempPage = hashUrl.split('/')[3];
    let projectNameStr = sessionStorage.getItem('projectName');
    setPage(tempPage);
    setProjectName(projectNameStr ? projectNameStr : '');
  }, []);

  /**
   * 功能描述 依据页面路由渲染面包屑组件的尾部文字
   * 
   * @return {string} 面包屑的末级页面名称
   */
  function getPageName(): string {
    switch(page) {
      case 'overview':
        return intl.get('PROJECT_OVERVIEW');
      case 'inference':
        return intl.get('ROOT_CAUSE_INFERENCE');
      case 'bigModel':
        return intl.get('BIG_MODEL_DIAGNOSTICS');
      default:
        return intl.get('PROJECT_OVERVIEW');
    }
  }

  return (<div className="slider-menu">
    <Breadcrumb>
      <Breadcrumb.Item href="#/kgom/packageList">
        <img src={home} />
        <span>{intl.get('PROJECT_LIST')}</span>
      </Breadcrumb.Item>
      <Breadcrumb.Item >
        <span>{projectName}</span>
      </Breadcrumb.Item>
      <Breadcrumb.Item>
        <span>{getPageName()}</span>
      </Breadcrumb.Item>
    </Breadcrumb>
  </div>);
};

export default TopMenu;

then i write a easy test code like this:

import TopMenu from './topMenu';
import React from 'react';
import renderer from 'react-test-renderer';

jest.mock('@/image/project/home.png', () => '../image/project/home.png');

describe('TopMenu Test', () => {
  it('render TopMenu', () => {
    const component = renderer.create(<TopMenu />);
    expect(component.toJSON()).toMatchSnapshot();
  });
});
when i run npm test, it calls this error: enter image description here

espicially this line: jest.mock('@/image/project/home.png', () => '../image/project/home.png'); I try many ways to rewrite this line, but it always error, when i not write this line, it calls that error: enter image description here

how do i write this hook component jest render test???



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source