MaksimL
MaksimL

Reputation: 314

Test custom react native hook with useAsyncStorage inside

How can I test custom react native hook which has inside useAsyncStorage hook?

This is my hook:

export const useCustomHook = () => {
  const storage = useAsyncStorage('item');
  const [state, setState] = useState<string | null>(null);
  useEffect(() => {
    if (!state) {
      storage.getItem().then(value => {
        setState(value ?? 'some value');
      });
    }
  }, [state, storage]);

  return state;
};

And I try to test it using react native testing library and jest. But got error (0 , _asyncStorage.useAsyncStorage) is not a function when I render hook

This is the part of the test and even without expect the hook is not rendered

import AsyncStorage from '../../../__mocks__/@react-native-async-storage/async-storage';
jest.mock('@react-native-async-storage/async-storage/jest/async-storage-mock');
describe('Test hook', () => {
  beforeEach(async () => {
    await AsyncStorage.setItem('item', 'value');
  });
  it('Should return item', () => {
    const { result } = renderHook(() => {
      useCustomHook();
    });
  });
});

Upvotes: 1

Views: 261

Answers (1)

NuttyJackJ
NuttyJackJ

Reputation: 320

Okay, I noticed that you have it imported from the mocks, which is the right thing to do.

What you need to do is mock the module by having your own implementation of the package's methods and modules.

So inside of the mock module that you created for AsyncStorage

I believe you have like this:

export module 'AsyncStorage' {

   getItem: jest.fn(),
   ...

}


So, you'd need to add a mock implementation of the hook inside of this mock module.

Here's the documentation for AsyncStorage hook API,

The change that you need is something like this:

export module 'AsyncStorage' {

   getItem: jest.fn(),
   // NOTE I just added the function as a type but this should be the 
   // implementation instead, so replace this with jest.fn() or whatever you 
   // are expecting the function to return / do
   useAsyncStorage: () => ({
      getItem: (
        callback?: ?(error: ?Error, result: string | null) => void,
       ) => Promise<string | null>,

   )}
   ...

}


Upvotes: 0

Related Questions