React Native测试失败:“TypeError:无法读取未定义的属性'fs'”

时间:2017-12-03 07:58:17

标签: react-native jestjs

当我运行npm test时:

➜  mobile git:(develop) ✗ npm test
> jest

 FAIL  __tests__/index.js
  ● Test suite failed to run

    TypeError: Cannot read property 'fs' of undefined

      at Object.<anonymous> (node_modules/react-native-cached-image/utils/fsUtils.js:9:12)
      at Object.<anonymous> (node_modules/react-native-cached-image/ImageCacheManager.js:5:13)
      at Object.<anonymous> (node_modules/react-native-cached-image/CachedImage.js:13:23)

我发现这与react-native-cached-imagefs的依赖性有关 我不得不以某种方式模仿fs吗?我尝试了几件事,但没有成功。

1 个答案:

答案 0 :(得分:3)

使用fs模拟组件

如果可能的话,我会建议您模拟 react-native-image-cache ,而不是模拟fs,因为fs被该包的一个依赖项使用。您可以看到the line listed in you're error

您可以像下面这样模拟react-native-image-cache:

jest.mock('react-native-img-cache', () => {
  return {
    DocumentDir: () => {},
    ImageCache: {
      get: {
        clear: () => {}
      }
    }
  }
})

在同样的问题上,应该可以模拟使用fs并导致错误的 react-native-fetch-blob 。 return语句的属性取决于image-cache lib使用的方法和属性。可能你不需要下面列出的那么多,但现在你知道可能不仅仅是fs。

jest.mock('react-native-fetch-blob', () => {
  return {
    DocumentDir: () => {},
    fetch: () => {},
    base64: () => {},
    android: () => {},
    ios: () => {},
    config: () => {},
    session: () => {},
    fs: {
      dirs: {
        MainBundleDir: () => {},
        CacheDir: () => {},
        DocumentDir: () => {},
      },
    },
    wrap: () => {},
    polyfill: () => {},
    JSONStream: () => {}
  }
})

模拟fs

如果您想要/需要专门模拟fs,您可以执行以下操作:

  1. 研究图书馆使用的测试react-native-cached-image
  2. 使用其中一个npm包来模拟fs:mock-fsjest-plugin-fsfake-fs
  3. 自己动手
  4. 有时甚至可以做类似的事情:

    fs = require("fs")
    fs.readFile = function (filename, cb) {
      cb(null, new Buffer("fake contents");
    };
    // etc
    

    但请记住,fs在依赖包中的某处使用。在这种情况下,我不确定代码是否正常工作,这就是我将其他选项放在顶部的原因。

相关问题