'How can I mock a custom function in jest?

This function is a custom hook which takes in async function and returns Loading, error state and trigger function

export function useAsync<T>(fn: () => PromiseLike<T>): AsyncReturn<T> {
  const logger = useLogger();

  const [state, setState] = useState<AsyncState<T>>({
    isLoading: false,
    hasError: false,
  });

  async function go() {
    setState((s) => ({ ...s, isLoading: true, hasError: false }));

    try {
      const result = await fn();
      setState((s) => ({ ...s, isLoading: false, result }));
      return result;
    } catch (error) {
      logger.error(error);
      setState((s) => ({ ...s, isLoading: false, hasError: true }));
      throw error;
    }
  }

  function setResult(action: SetStateAction<T>): void {
    if (action instanceof Function) {
      setState((previous) => {
        const result = previous.result
          ? action(previous.result)
          : previous.result;

        return {
          ...previous,
          isLoading: false,
          result,
        };
      });
    } else {
      setState((previous) => ({
        ...previous,
        isLoading: false,
        result: action,
      }));
    }
  }

  return [state, go, setResult];
}

Tried mocking this by using the below mock function

  ...jest.requireActual("../../../../hooks/use-async"),
  useAsync: jest.fn((fn) => {
const result=await fn()
    return [
      {
        hasError: false,
        isLoading: false,
        result,
   async () => await fn(),
      () => {},
      },
    
    ];
  }),
}));

But the issue is awaiting makes this function behave like a promise which is why jest is crying and without awaiting a pending promise is returned. Can someone help on how can i mock this function?



Sources

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

Source: Stack Overflow

Solution Source