您好,欢迎来到12图资源库!分享精神,快乐你我!我们只是素材的搬运工!!
  • 首 页
  • 当前位置:首页 > 开发 > WEB开发 >
    深入理解JavaScript错误和堆栈追踪(7)
    时间:2017-04-25 15:33 来源:网络整理 作者:网络 浏览:收藏 挑错 推荐 打印

        if (undefined === expected && undefined === _actual) showDiff = false

        if (true !== config.showDiff) showDiff = false

     

        if (!ok) { 

            msg = util.getMessage(this, arguments); 

            var actual = util.getActual(this, arguments); 

     

            // This is the relevant line for us 

            throw new AssertionError(msg, { 

                    actual: actual 

                , expected: expected 

                , showDiff: showDiff 

            }, (config.includeStack) ? this.assert : flag(this, 'ssfi')); 

        } 

    }; 

    assert方法负责检查断言布尔表达式是否通过。如果不通过,我们则实例化一个AssertionError。不知道你注意到没,在实例化AssertionError时,我们也给它传递了一个堆栈追踪函数指示器(ssfi),如果配置的includeStack处于开启状态,我们通过将this.assert本身传递给它来为用户显示整个堆栈跟踪。反之,我们则只显示ssfi标记中存储的内容,隐藏掉堆栈跟踪中更多的内部实现细节。

    现在让我们来讨论下一行和我们相关的代码吧:

    `new Assertion(obj, msg, ssfi, true).to.have.property('length');` 

    As you can see here we are passing the content we’ve got from the ssfi flag when creating our nested assertion. This means that when the new assertion gets created it will use this function as the starting point for removing unuseful frames from the stack trace. By the way, this is the Assertion constructor: 如你所见,我们在创建嵌套断言时将从ssfi标记中的内容传递给了它。这意味着新创建的断言会使用那个方法作为起始调用帧,从而可以从堆栈追踪中清除没有的调用栈。顺便也看下Assertion的构造器吧:

    function Assertion (obj, msg, ssfi, lockSsfi) { 

        // This is the line that matters to us 

        flag(this, 'ssfi', ssfi || Assertion); 

        flag(this, 'lockSsfi', lockSsfi); 

        flag(this, 'object', obj); 

        flag(this, 'message', msg); 

     

        return util.proxify(this); 

    不知道你是否还记的我先前说过的addChainableMethod方法,它使用自己的父级方法设置ssfi标志,这意味着它始终处于堆栈的底部,我们可以删除它之上的所有调用帧。

    通过将ssfi传递给嵌套断言,它只检查我们的对象是否具有长度属性,我们就可以避免重置我们将要用作起始指标器的调用帧,然后在堆栈中可以看到以前的addChainableMethod。

    这可能看起来有点复杂,所以让我们回顾一下我们想从栈中删除无用的调用帧时Chai中所发生的事情:

    当我们运行断言时,我们将它自己的方法作为移除堆栈中的下一个调用帧的参考

    断言失败时,我们会移除所有我们在参考帧之后保存的内部调用帧。

    如果存在嵌套的断言。我们必须依旧使用当前断言的父方法作为删除下一个调用帧的参考点,因此我们把当前的ssfi(起始函数指示器)传递给我们所创建的断言,以便它可以保存。

    【编辑推荐】

    适用于仪表盘项目的7个优秀JavaScript库

    JavaScript即未来:介绍14个JavaScript的框架和库

    在Node.js中看JavaScript的引用

    从JavaScript到TypeScript - 模块化和构建

    (责任编辑:admin)