【问题标题】:How do you test hooks with no trigger event like a click如何在没有触发事件(如点击)的情况下测试钩子
【发布时间】:2020-06-23 06:23:27
【问题描述】:

只要有某种类型的 onClick、onChange 等,关于如何运行钩子测试似乎有很多内容,但是如果您像下面这样将该函数传递给您的事件处理组件怎么办?

const Content: FC<Props> = ({ activeTab }) => {
  const [count, setCount] = useState<number>(0);

  function handleDateUpdate(dates: object) {
    const totalCount = new GetTotal(dates, activeTab);
    setCount(totalCount.totalAttendances());
  }

  useEffect(() => {
    if (activeTab === 'Year') {
      handleDateUpdate(new Date());
    }
  });

  return (
    <Container>
        {activeTab === 'Month' && (
          <Datepicker handleDateUpdate={handleDateUpdate} />
        )}
      <TotalAttendences count={count} />
    </Container>
  );
}

我想编写一个测试来检查 useEffect 中的 if 语句以及 handleDateUpdate 以确保它正在执行我想要的操作。

【问题讨论】:

    标签: reactjs jestjs react-hooks react-testing-library


    【解决方案1】:

    如果要测试是否调用了handleDateUpdate,我建议将其提取到帮助文件中,然后使用export function 将其导出。然后,通过执行以下操作将整个帮助文件导入到定义组件的文件中: import * as dateHelpers from '../path/to/file';

    这样当你调用组件中的函数时,你就可以使用dateHelpers.handleDateUpdate。这将确保正确注入依赖项,以便您能够监视您在组件中调用的 handleDateUpdate 函数的实例,以确保它被正确调用(或不被正确调用)。

    由于activeTab&lt;Content /&gt; 的属性,我将通过执行以下操作来测试useEffect

    import { shallow } from enzyme;
    // I'm using enzyme here, but you could use whatever React testing library you choose
    import * as dateHelpers from '../path/to/file/'
    
    describe('<Content />', () => {
      let dateUpdateSpy;
      beforeEach(() => {
        dateUpdateSpy = jest.spyOn(dateHelpers, 'handleDateUpdate'); 
      })
    
      afterEach(() => {
        jest.clearAllMocks()
      })
    
      it('should invoke handleDateUpdate() when the activeTab prop equals "Year"'), () 
      => {
        shallow(<Content activeTab="Year" />);
    
        expect(dateUpdateSpy).toHaveBeenCalledWith(new Date());
      }
    
    
      it('should not invoke handleDateUpdate() when the activeTab prop does not equal 
      "Year"'), () => {
        shallow(<Content activeTab="Month" />);
    
        expect(dateUpdateSpy).not.toHaveBeenCalled();
      }
    }
    

    最后,您应该将activeTab 添加为useEffect 的依赖项,因为您只想在activeTab 更改时运行该回调函数。它将在挂载时运行,但如果由于activeTab 更改以外的任何原因重新渲染,您将不必要地重新运行useEffect。所以我将其更改为:

    useEffect(() => {
      if (activeTab === 'Year') {
        dateHelpers.handleDateUpdate(new Date());
      }
    }, [activeTab]);
    ``
    

    【讨论】:

    • 干杯,有没有办法将所有内容保存在一个文件中?
    • 这是一个想法:您可以将函数留在原处并测试以查看 setCount 是通过模拟 useState 调用的。 const mockSetState = jest.fn(); jest.spyOn(React, 'useState').mockImplementation(init =&gt; [init, mockSetState]); 然后你的断言会根据你在测试中传递给&lt;Content /&gt; 的道具检查是否调用了mockSetState
    猜你喜欢
    • 2017-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多