【问题标题】:How to skip jest compile error and run test?如何跳过开玩笑编译错误并运行测试?
【发布时间】:2020-12-02 00:53:51
【问题描述】:

这是我的 vue.js 代码:

export default {
  name: 'App',
  components: {
  },
  created() {
    let t = typeof t === 'undefined' ? {} : t; // ISSUE LINE
  }
}

ISSUE LINE 可以在浏览器中成功运行,没有任何错误,并通过 vue-cli 编译过程。但是,当我尝试运行这个组件时,它可能会报告编译错误:

ReferenceError: Cannot access 't' before initialization

所以如果应用程序可以在浏览器中运行,为什么它不能在开玩笑中运行呢?我可以跳过这个编译错误吗?

【问题讨论】:

    标签: javascript vue.js jestjs babeljs babel-jest


    【解决方案1】:

    ReferenceError 不是编译而是运行时错误。 let t = typeof t === 'undefined' ? {} : t 是无效的 ES6 代码。 let 是块范围的,在分配之前处于临时死区,因此在分配期间引用变量是错误的。

    这在 Jest 中不起作用,因为 Node.js 完全支持 ES6 并且不需要转译为 ES5,而在浏览器构建中它被转译为:

    var t = typeof t === 'undefined' ? {} : t;
    

    var声明被提升,所以t变量在赋值的时候就定义好了,所以和:

    var t; // t === undefined
    // ...everything that happens in this scope...
    t = typeof t === 'undefined' ? {} : t; // always results in t = {}
    

    条件没有用,因为它永远不会到达else,正确的写法是:

    let t = {};
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      相关资源
      最近更新 更多