在Jest上模拟react-native-async-storage

时间:2019-05-21 20:15:53

标签: react-native jestjs asyncstorage

我正在测试依赖于@react-native-community/async-storage的函数,因此显然我的测试必须模拟该库。

所以我在jestSetupFile.js里面做这个:

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

这是来自https://github.com/react-native-community/react-native-async-storage/blob/master/docs/Jest-integration.md的直接指示

但是,导出的文件具有type关键字,我的JavaScript环境无法解析这些关键字:

  ● Test suite failed to run

    /Users/someuser/myprojects/myproject/node_modules/@react-native-community/async-storage/jest/async-storage-mock.js:6
    type KeysType = Array<string>;
         ^^^^^^^^

    SyntaxError: Unexpected identifier

果然,当我在该路径下检查async-storage-mock.js文件时,它包含type关键字,我相信这是此问题的根本原因。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

我的解决方案是切换到mock-async-storage

我的jestSetupFile.js

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

^^在我的测试脚本本身开始时,上面的模拟代码无法正常工作,尽管我的其他模拟代码通常也可以在此处运行。仅当添加到我在package.json中定义的jestSetupFile.js中时,此方法才起作用:

"jest:"  {
   "setupFiles": [
      "./jestSetupFile.js"
    ]
}