开玩笑地监视自定义挂钩内的函数

mai*_*idi 6 jestjs react-hooks

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

这是我尝试过的:

myComponent.tsx

...
const { doSomething} = useCustom();
doSomething('a','b');
...
Run Code Online (Sandbox Code Playgroud)

useCustom.ts

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

  return { doSomething };
Run Code Online (Sandbox Code Playgroud)

myComponent.spec.ts

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

mai*_*idi 11

我现在设法这样做:

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');
 });
Run Code Online (Sandbox Code Playgroud)