useWorker icon indicating copy to clipboard operation
useWorker copied to clipboard

How to test a custom hook using useWorker?

Open NandoSangenetto opened this issue 3 years ago • 2 comments

I've been playing with useWorker, and it has been working on the browser.

I tried to create a test for a custom hook that is using the useWorker and got many errors. I've tried to install jsdom-worker, but I keep receiving errors.

I'm going to share the errors: image ☝️ with jsdom-worker

image ☝️ without `jsdom-worker`

What kind of setup do I need to do to make it work using jest?

NandoSangenetto avatar Sep 12 '22 22:09 NandoSangenetto

More context, this is the hook I'm testing:

const transactionTransformer = (input: InputType) => {
  // expensive stuff happening here
  return transactionList;
};

const useRecentTransactions = (params?: UseRecentTransactionsParams): UseRecentTransactionsType => {
  const [transactions, setTransactions] = useState<Array<RecentTransaction>>([]);
  const { lastMessage, connectionStatus } = useNetwork({ url: params?.url });
  const [transactionWorker] = useWorker(transactionTransformer);

  useEffect(() => {
    const fetchTransactions = async () => {
      if (connectionStatus === 'Open' && lastMessage !== undefined) {
        const transactionList = await transactionWorker(lastMessage);

        setTransactions((prevTransaction) =>
                transactionList.concat(prevTransaction).slice(0, NUMBER_OF_TRANSACTIONS));
      }
    };

    fetchTransactions();
  }, [connectionStatus, lastMessage, setTransactions, transactionWorker]);

  return {
    transactions,
    connectionStatus,
  };
};

And the test file:

 it('should transform blocks and operations into transactions', async () => {
    const { result } = renderHook(() => useRecentTransactions({ url: WEBSOCKET_URL }), {
      wrapper: ({ children }) => <ContainerProvider>{children}</ContainerProvider>,
    });

    console.log(result.current);
});

NandoSangenetto avatar Sep 12 '22 22:09 NandoSangenetto

It seems related to https://github.com/developit/jsdom-worker/issues/16

NandoSangenetto avatar Sep 13 '22 00:09 NandoSangenetto