安装了react-native-async-storage

时间:2019-03-29 13:49:55

标签: react-native jestjs babel-jest

在我的react native项目中,我最近安装了节点模块react-native-async-storage,因为我收到有关不赞成使用'react-native'并将其移至单个模块的本机软件包的警告。

安装@react-native-community/async-storage后,我的笑话测试失败了。

首先跟随error: unexpected token at position 0

在文件中:

persistence.js

import AsyncStorage from '@react-native-community/async-storage';

storeData = async ({ key, value }) => {
  try {
    await AsyncStorage.setItem(key, value);
  } catch (error) {
    // Error saving data
  }
}

retrieveData = async (key) => {
  try {
    const value = await AsyncStorage.getItem(key);
    if (value !== null) {
      // Our data is fetched successfully
      return value;
    }
  } catch (error) {
    // Error retrieving data
  }
}

module.exports = {
  storeData,
  retrieveData
}

所以我认为这与某些babel配置有关,因为上次我从@ react-native-community安装软件包时遇到了类似的情况

因此,在package.json中的transformIgnorePatterns中添加了以下内容:

  "jest": {
    "preset": "react-native",
    "transformIgnorePatterns": [
      "node_modules/(?!react-native|@react-native-community/async-storage|native-base-shoutem-theme|@shoutem/animation|@shoutem/ui|tcomb-form-native)"
    ]
  }

但是现在我遇到了一个新错误。 @RNCommunity/AsyncStorage: NativeModule.RCTAsyncStorage is null.

我正在粘贴屏幕截图以显示我的项目目录,以便您可以了解哪些配置文件可供使用。 enter image description here

正如我所看到的,大多数相关主题都是关于模拟asyncStorage函数的,我尝试这样做没有任何运气。我在唯一的测试文件中添加了以下内容:

import MockAsyncStorage from 'mock-async-storage';

beforeAll(() => { 
  const mockImpl = new MockAsyncStorage()
  jest.mock('AsyncStorage', () => mockImpl)
  snapshot = renderer.create(<App />);
})

afterAll(() => {
  jest.unmock('AsyncStorage')
});

仍然没有雪茄。我尝试添加setupFilesAfterEnv.js的配置(如其他答案所示),但也没有成功。

6 个答案:

答案 0 :(得分:1)

您需要将这段代码添加到setupTestFrameworkScriptFile

    import { NativeModules } from 'react-native';
NativeModules.RNCAsyncStorage = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  removeItem: jest.fn(),
  mergeItem: jest.fn(),
  clear: jest.fn(),
  getAllKeys: jest.fn(),
  flushGetRequests: jest.fn(),
  multiGet: jest.fn(),
  multiSet: jest.fn(),
  multiRemove: jest.fn(),
  multiMerge: jest.fn(),
};

答案 1 :(得分:1)

我找到了一种模拟@react-native-community/async-storage

的方法

在我项目的根目录(与__test__目录相同)中,我创建了一个目录结构,如下所示:

_mocks__/@react-native-community/async-storage/index.js

在index.js中,我模拟了以下功能:

let cache = {};
export default {
  setItem: (key, value) => {
    return new Promise((resolve, reject) => {
      return (typeof key !== 'string' || typeof value !== 'string')
        ? reject(new Error('key and value must be string'))
        : resolve(cache[key] = value);
    });
  },
  getItem: (key, value) => {
    return new Promise((resolve) => {
      return cache.hasOwnProperty(key)
        ? resolve(cache[key])
        : resolve(null);
    });
  },
  removeItem: (key) => {
    return new Promise((resolve, reject) => {
      return cache.hasOwnProperty(key)
        ? resolve(delete cache[key])
        : reject('No such key!');
    });
  },
  clear: (key) => {
    return new Promise((resolve, reject) => resolve(cache = {}));
  },

  getAllKeys: (key) => {
    return new Promise((resolve, reject) => resolve(Object.keys(cache)));
  },
}

在我的测试文件中,我添加了以下内容:

beforeAll(() => { 
  jest.mock('@react-native-community/async-storage');
})

目录结构的屏幕截图: enter image description here

这成功了。我在这里找到了灵感:https://github.com/react-native-community/react-native-async-storage/issues/39

答案 2 :(得分:1)

编辑 忽略我的答案,而是这样做: https://github.com/react-native-community/async-storage/blob/LEGACY/docs/Jest-integration.md

感谢@Krizzo

另一个基于@Rasmus Puls的Jest版本,但具有jest函数-将添加到您的jest模拟文件中。

jest.mock('@react-native-community/async-storage', () => { 
  let cache = {};
  return {
    setItem: jest.fn((key, value) => {
      return new Promise((resolve, reject) => {
        return (typeof key !== 'string' || typeof value !== 'string')
          ? reject(new Error('key and value must be string'))
          : resolve(cache[key] = value);
      });
    }),
    getItem: jest.fn((key, value) => {
      return new Promise((resolve) => {
        return cache.hasOwnProperty(key)
          ? resolve(cache[key])
          : resolve(null);
      });
    }),
    removeItem: jest.fn((key) => {
      return new Promise((resolve, reject) => {
        return cache.hasOwnProperty(key)
          ? resolve(delete cache[key])
          : reject('No such key!');
      });
    }),
    clear: jest.fn((key) => {
      return new Promise((resolve, reject) => resolve(cache = {}));
    }),
    getAllKeys: jest.fn((key) => {
      return new Promise((resolve, reject) => resolve(Object.keys(cache)));
    }),
  }
});

答案 3 :(得分:0)

以下是解决此问题的方法:

  1. 在项目的根目录中,创建 __ mocks __ / @ react-native-community 目录。
  2. 在该文件夹中,创建一个 async-storage.js 文件。
  3. 复制将以下内容粘贴到该文件中:
export default from '@react-native-community/async-storage/jest/async-storage-mock'

按照documentation

以防其他人像我一样寻找这个东西。

答案 4 :(得分:0)

您可以将其添加到测试文件中。

jest.mock("@react-native-community/async-storage", () =>
  require("@react-native-community/async-storage/jest/async-storage-mock"),
);

例如

import React from "react";

jest.mock("@react-native-community/async-storage", () =>
  require("@react-native-community/async-storage/jest/async-storage-mock"),
);

describe("Example test", () => {
  it("should work", () => {
    ...
  });
});

答案 5 :(得分:0)

查看 documentation by the team,(来自 Francois Nadeau 提供的答案)我能够将“mocking with jest setup.js file”选项的行更改为下方,并解决了完全相同的问题。

import mockAsyncStorage from '@react-native-community/async-storage/jest/async-storage-mock';
jest.mock('@react-native-community/async-storage', () => mockAsyncStorage);

请注意路径已更改。