1

The following hook should be tested.

export function useSomethingSaver() {
  let somethingMutation = useMutation(async (newSomething) => {
    return await saveSomething(newSomething)
  })

  return {
    saveSomething: somethingMutation.mutate,
    saveSomethingAsync: somethingMutation.mutateAsync,
    isLoading: somethingMutation.isLoading,
    isError: somethingMutation.isError,
  }
}

Now I want to test if the saveSomething method is called with the right parameters when calling saveSomethingAsync.

import { act, renderHook, waitFor } from '@testing-library/react-native'

...

it('Something can be saved', async () => {
  saveSomething.mockImplementation(() => SOMETHING_DATA)

  const wrapper = ({ children }) => (
    <BaseContexts queryClient={queryClient}>{children}</BaseContexts>
  )

  const { result } = renderHook(() => useSomethingSaver(), { wrapper })

  await act(async () => {
    await result.current.saveSomething(SOMETHING_SAVE_DATA)
  })
  await waitFor(() => !result.current.isLoading)

  expect(saveSomething).toBeCalledWith(SOMETHING_SAVE_DATA)
})

The test is green but it puts out the following error message:

  console.error
    Warning: You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);

      at printWarning (node_modules/react/cjs/react.development.js:209:30)
      at error (node_modules/react/cjs/react.development.js:183:7)
      at node_modules/react/cjs/react.development.js:2559:15
      at tryCallOne (node_modules/promise/lib/core.js:37:12)
      at node_modules/promise/lib/core.js:123:15
      at flush (node_modules/asap/raw.js:50:29)

The problem is that the act() call is clearly awaited. Can someone please explain to me, why this error message is shown?

EDIT: act-statement with semicolons:

const { result } = renderUseSomethingSaver();

await act(async () => {
   await result.current.saveSomethingAsync(SOMETHING_SAVE_DATA);
});
await waitFor(() => !result.current.isLoading);
rKatex
  • 77
  • 1
  • 8
  • Is this a problem due to lack of semicolons? [What are the rules for JavaScript's automatic semicolon insertion (ASI)?](https://stackoverflow.com/q/2846283) – VLAZ Sep 15 '22 at 08:55
  • I have tried it with semicolons (automatically set by prettier) and there was no difference. I copied the code-block with semicolons into my question. – rKatex Sep 15 '22 at 09:06
  • The code you copied doesn't show a semicolon *before* `await act(` - is there one there? – VLAZ Sep 15 '22 at 09:07
  • Yes, there was a semicolon at the end of the statement before the await act. I also copied it into my edit – rKatex Sep 15 '22 at 09:10

0 Answers0