2
votes

I am learning TDD and trying to implement async storage tests by following the guides from https://react-native-async-storage.github.io/async-storage/docs/advanced/jest/ I have followed the installation and currently trying to mock async storage in my first test.

I created a simple test.

import React from 'react';
import {render, fireEvent} from 'react-native-testing-library';
import UserWelcome from '../UserWelcome';
import AsyncStorage from '@react-native-async-storage/async-storage';

describe('UserWelcome', () => {
  describe('User enters a name and stores in async local storage', () => {
    const firstTimeUser = 'user001';
    let getByTestId;

    beforeEach(() => {
      ({getByTestId} = render(<UserWelcome />));

      fireEvent.changeText(getByTestId('username'), firstTimeUser);
      fireEvent.press(getByTestId('submitUsername'));
    });

    it('checks if Async Storage is used', async () => {
      await asyncOperationOnAsyncStorage();

      expect(AsyncStorage.getItem).toBeCalledWith('currentUser');
    });
  });
});

Then I get the error ReferenceError: asyncOperationOnAsyncStorage is not defined Could someone give me a hand on where I am supposed to get the asyncOperationOnAsyncStorage() function from. The docs just say

Each public method available from Async Storage is a mock function, that you can test for certain condition, for example, if .getItem has been called with a specific arguments:
1

1 Answers

3
votes

I think you have misunderstood the documentation. asyncOperationOnAsyncStorage is just an example method that is defined in the documentation, you will have to replace asyncOperationOnAsyncStorage with the method that you have some async storage operation.

So essentially asyncOperationOnAsyncStorage will be the method that will contain the async storage logic.

asyncOperationOnAsyncStorage = () => { 
   await AsyncStorage.setItem('currentUser', value)
}

Which you will test with Jest.