【问题标题】:Unit Test with Jest gives TypeError: File.test.js: Cannot read property 'toString' of undefined带有 Jest 的单元测试给出 TypeError: File.test.js: Cannot read property 'toString' of undefined
【发布时间】:2020-12-15 14:27:11
【问题描述】:

我一直在使用 Expo CLI 在 React Native 中工作,最近开始面临我的单元测试由于一个常见原因而失败的问题。堆栈跟踪如下

Cannot read property 'toString' of undefined

      at Converter.toBase64 (node_modules/convert-source-map/index.js:61:46)
      at Converter.toComment (node_modules/convert-source-map/index.js:65:21)
      at generateCode (node_modules/@babel/core/lib/transformation/file/generate.js:78:76)
      at run (node_modules/@babel/core/lib/transformation/index.js:55:33)
          at run.next (<anonymous>)
      at transform (node_modules/@babel/core/lib/transform.js:27:41)
          at transform.next (<anonymous>)
      at evaluateSync (node_modules/gensync/index.js:244:28)
      at sync (node_modules/gensync/index.js:84:14)

我的节点版本是 node:12.18.4。我想知道是什么导致了这些错误,因为一切正常。在我的本地系统上,它们运行良好,但偶尔会出现 CI 过程往往会导致它们随机失败,这会影响整体代码覆盖率。

我尝试运行的单元测试非常简单,如下所示

it('Renders Strings as expected', () => {
  expect(received).toStrictEqual(expected)
})

【问题讨论】:

    标签: react-native jestjs expo babeljs babel-jest


    【解决方案1】:

    对于那些仍在四处游荡以寻找上述问题答案的人。 问题在于需要处理此异常的库本身 convert-source-map。

    我分叉了实际的存储库并在第 64 行 toBase64 方法中处理了该异常。现在这个方法看起来有点像

    Converter.prototype.toBase64 = function () {
      var json = this.toJSON();
      return (SafeBuffer.Buffer.from(json, 'utf8') || "").toString('base64');
    };
    

    现在一切正常。

    原来的方法是这样的

    Converter.prototype.toBase64 = function () {
      var json = this.toJSON();
      return SafeBuffer.Buffer.from(json, 'utf8').toString('base64');
    };
    

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 1970-01-01
      • 2019-12-15
      • 2018-05-26
      • 1970-01-01
      • 2021-06-25
      • 2018-11-01
      • 2020-09-04
      • 2017-08-19
      相关资源
      最近更新 更多