React Native 中的 Jest 和异步存储

Jest and Async Storage in React Native

我正在学习 TDD 并尝试按照 https://react-native-async-storage.github.io/async-storage/docs/advanced/jest/ 中的指南实施异步存储测试 我已经完成了安装,目前正在尝试在我的第一次测试中模拟异步存储。

我创建了一个简单的测试。

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');
    });
  });
});

然后我得到错误 ReferenceError: asyncOperationOnAsyncStorage 未定义 有人可以帮助我了解我应该从哪里获取 asyncOperationOnAsyncStorage() 函数。文档只是说

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:

我认为您误解了文档。 asyncOperationOnAsyncStorage 只是文档中定义的示例方法,您必须将 asyncOperationOnAsyncStorage 替换为您具有一些异步存储操作的方法。

所以基本上 asyncOperationOnAsyncStorage 将是包含异步存储逻辑的方法。

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

您将使用 Jest 对其进行测试。