【问题标题】:Jest spy on a function inside a custom hook开玩笑地监视自定义钩子中的函数
【发布时间】:2021-10-09 12:17:05
【问题描述】:

我有一个名为useCustom 的自定义钩子,它实现了一个名为doSomething 的函数。 在我的反应组件中,我想监视 doSomething 它已被使用某些值调用。但它永远不会被调用。模拟或监视 doSomething 方法的正确方法是什么?

这是我尝试过的:

myComponent.tsx

...
const { doSomething} = useCustom();
doSomething('a','b');
...

useCustom.ts

export const useCustom= () => {
  const doSomething = (param1, param2): void => {
    ...
  };

  return { doSomething };

myComponent.spec.ts

it('should call dosomething', () => {
    const doSomethingSpy= jest.spyOn(useCustom(), 'doSomething');
    ...
    expect(doSomethingSpy).toHaveBeenCalledWith('a','b');
});

【问题讨论】:

    标签: jestjs react-hooks


    【解决方案1】:

    我现在设法做到了:

    import * as useCustomHook from '@hooks/useCustom';
    
    it('should call dosomething', () => {
        const doSomethingMock= jest.fn();
        jest.spyOn(useCustomHook, 'useCustom').mockImplementation(() => {
          return {
             doSomething: doSomethingMock,
          };
         });
         ...
         expect(doSomethingMock).toHaveBeenCalledWith('a','b');
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-17
      • 2019-05-08
      • 2023-04-04
      • 2017-07-14
      • 2021-11-17
      • 2021-12-10
      • 2020-05-29
      • 2018-08-10
      相关资源
      最近更新 更多