简体   繁体   English

我如何覆盖javascript代码模式|| {}

[英]How do I cover the javascript code pattern || {}

I am using JSCover running my Jasmine SpecRunner, which inspects a code fragment of the sort: 我正在使用运行我的Jasmine SpecRunner的JSCover,它检查了以下代码片段:

var MyRootObject = MyRootObject || {};

My goal is to bring coverage up to 100%, but I am not sure how best to cover this method of initialising the MyRootObject. 我的目标是使覆盖率达到100%,但是我不确定如何最好地涵盖这种初始化MyRootObject的方法。

This pattern is used at the start of every library javascript file, to ensure that the order in which the files are loaded is unimportant (and the functions and variables inside are $.extend'ed). 每个库javascript文件的开头都使用此模式,以确保文件的加载顺序不重要(并且$ .extend'ed里面的函数和变量)。

The problem basically is that the first and only time this script is loaded in the SpecRunner, it runs only one side of this test, leaving the other path untested. 基本上,问题在于,第一次且唯一一次在SpecRunner中加载此脚本时,它仅运行此测试的一侧,而另一路径未经测试。

After digging around, I found a solution that works for me, of course, your mileage may vary: 深入研究后,我发现了一个适合我的解决方案,当然,您的工作量可能会有所不同:

var MyRootObject = MyRootObject || {};
$.extend(true, MyRootObject, {...});

I have replaced with: 我已替换为:

var MyRootObject = $.extend(true, MyRootObject, {...});

Internally inside JQuery, if the target (MyRootObject) is null or undefined, it automatically assigns the target inside the function to be {}. 在JQuery内部,如果目标(MyRootObject)为null或未定义,它将自动将函数内的目标分配为{}。 By using an external library (which I was already using), I no longer have a conditional path I am not following, as this is delegated to the JQuery library. 通过使用外部库(我已经在使用),我不再有我不遵循的条件路径,因为它被委托给了JQuery库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何让 JavaScript canvas 覆盖整个屏幕? - How do I make the JavaScript canvas cover the whole screen? 如何让我的代码在谷歌表格上覆盖多个标签? - How do I get my code on google sheets to cover multiple tabs? 如何使用vanilla Javascript按顺序加载新URL以覆盖浏览器历史记录? - How do I load new URLs sequentially to cover up browser history using vanilla Javascript? 使用 background-size:cover 后如何更改 javascript 中的背景 url? - How do I change the background url in javascript after using background-size: cover? 如何使用本机Javascript Promise进行延迟模式? - How do I do a deferred pattern with native javascript promises? 如何调用此JavaScript模式,以及如何以正确的方式使用它? - How is this JavaScript pattern called and how do I use it in the right way? 如何在Javascript中将调解器模式与调解器的多个实例一起使用? - How do I use the mediator pattern with multiple instances of a mediator in Javascript? 如何在Javascript模块模式中使用私有函数/变量? - How do I use private functions/variables in the Javascript module pattern? 如何在JavaScript中实现这种Java模式(使用继承)? - How do I implement this java pattern in JavaScript (using inheritance)? 如何使用依赖于变量的模式执行Javascript匹配? - How do I perform a Javascript match with a pattern that depends on a variable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM