【问题标题】:React Native tests failing: "TypeError: Cannot read property 'fs' of undefined"React Native 测试失败:“TypeError:无法读取未定义的属性‘fs’”
【发布时间】:2017-12-03 07:58:16
【问题描述】:

当我运行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 吗?我尝试了几件事,但没有成功。

【问题讨论】:

    标签: react-native jestjs


    【解决方案1】:

    使用 fs 模拟组件

    如果可能,我建议您不要模拟 fs,而是模拟 react-native-image-cache,因为 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. 自己动手

    有时甚至可以这样做:

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

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

    【讨论】:

      猜你喜欢
      • 2020-01-08
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 2019-02-17
      • 2020-11-05
      • 2020-04-17
      相关资源
      最近更新 更多