【问题标题】:Jest: TypeError: replaceAll is not a function笑话:TypeError:replaceAll 不是函数
【发布时间】:2021-03-25 11:31:26
【问题描述】:

String.prototype.replaceAll() 是一种有用的方法,在构建和执行时一切正常。但是,所有 Jest 测试都失败并出现以下错误:

TypeError: replaceAll is not a function

这些是我的依赖项:

"dependencies": {
  "core-js": "^3.6.5",
  "vue": "^2.6.11",
  "vue-class-component": "^7.2.3",
  "vue-i18n": "^8.22.0",
  "vue-property-decorator": "^8.4.2",
  "vue-router": "^3.3.4",
  "vuex": "^3.5.1"
},
"devDependencies": {
  "@vue/test-utils": "^1.1.0",
  "jest-junit": "^12.0.0",
  "ts-jest": "^26.4.1",
  "typescript": "~3.9.3",
  "vue-jest": "^3.0.7",
  "vue-template-compiler": "^2.6.10"
},

如何解决此问题?

【问题讨论】:

    标签: javascript node.js jestjs


    【解决方案1】:

    问题

    发生这种情况是因为 replaceAll 是一个新功能,并非在所有浏览器和旧 Node.js 版本中都实现,如另一个答案中所述。你可以在Can I Use看到哪些浏览器支持它:

    但是,您可以添加一个 polyfill 来支持旧版浏览器(如果需要),而不是使用带有 RegExp 的 .replace。就我而言,我使用的是 Electron,所以我只需要为 Jest 使用它。

    垫片可以是found here

    解决办法

    用作浏览器的 polyfill

    1. 使用npm i string.prototype.replaceallyarn add string.prototype.replaceall 作为依赖项安装;

    2. 在您的项目中添加以下代码。只需在一处添加即可。

    import replaceAllInserter from 'string.prototype.replaceall';
    
    replaceAllInserter.shim();
    

    仅在 Jest 中使用

    更新 Node.js

    正如 @leonheess 在 cmets 中提到的,您可以将 Node.js 更新到更新的版本。您将需要一个使用version 8.5 from V8 的版本,这是实现.replaceAll 的时间。

    根据list available on the Node.js website,两个版本都没有使用V8 8.5,但是从Node.js 15.0.0开始,使用的是V8的8.6版本。所以,升级到 Node.js v15 或更高版本。

    用作 polyfill

    如果您只想为 Jest 解决此问题,您可以按照in this issue 所述进行操作:

    1. 使用npm i -D string.prototype.replaceallyarn add -D string.prototype.replaceall 作为开发依赖项安装;

    2. 修改您的 Jest 配置,添加 setupFilesAfterEnv 属性,如下所示:

    {
      "jest": {
        "setupFilesAfterEnv": ["<rootDir>/jestSetup.js"]
      }
    }
    
    1. 将以下代码添加到您的 jestSetup 文件中:
    import replaceAllInserter from 'string.prototype.replaceall';
    
    replaceAllInserter.shim();
    

    【讨论】:

      【解决方案2】:

      这很可能是因为 String.prototype.replaceAll 没有在 Node.js 中实现(至少在版本 v14.15.0 中)。

      您可以使用的另一种选择是正则表达式,如本例所示:

      const str = 'foo-foo';
      const regex = /foo/g; // Note the 'g' flag, which matches all occurrences of the expression
      
      console.log(str.replace(regex, 'bar')); // 'bar-bar'
      

      您可以查看here 了解更多关于正则表达式的信息。

      【讨论】:

      • 如果你需要传递一些随机字符串。也许带有属性的html标签。那么这将成为更大的问题。
      猜你喜欢
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 2019-07-15
      • 2021-02-26
      • 2020-02-24
      • 1970-01-01
      • 2018-10-08
      • 1970-01-01
      相关资源
      最近更新 更多