【问题标题】:Jest and Async Storage in React NativeReact Native 中的 Jest 和异步存储
【发布时间】:2021-03-18 23:21:53
【问题描述】:

我正在学习 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:

【问题讨论】:

    标签: react-native jestjs tdd


    【解决方案1】:

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

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

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

    您将使用 Jest 进行测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 2019-10-30
      • 2019-10-25
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多