2011-01-09 50 views
0

我想使用YUI3测试框架来测试声明的已定义函数的存在。在Safari和FireFox中,尝试使用isNotUndefined,isUndefined或isFunction失败。我期望那些抛出一个可以由测试框架处理的异常。如何在YUI3中使用Assert.isUndefined()和Assert.isNotUndefined()?

Y 
Object 
Y.Assert 
Object 
Y.Assert.isNotUndefined(x, "fail message") 
ReferenceError: Can't find variable: x 
Y.Assert.isUndefined(x, "fail message") 
ReferenceError: Can't find variable: x 
Y.Assert.isFunction(x, "fail message") 
ReferenceError: Can't find variable: x 

但是,相反,我从来没有看到失败的消息和测试的剩余部分不运行,因为在路上...解释越来越不有损这些目的的函数,还是我误解了框架?

我的直觉告诉我,鉴于上面的代码中,只有上面的代码,

Y.Assert.isUndefined(x, "fail message") 

应继续没有错误(因为x是未申报),并

Y.Assert.isNotUndefined(x, "fail message") 

记录这一消息“失败消息”(因为x未声明)。

但是,由于ReferenceError,没有办法(使用这些YUI3方法)来测试未声明的对象。相反,我留下了一些非常丑陋的断言代码。我不能使用

Y.Assert.isNotUndefined(x) 
ReferenceError: Can't find variable: x 

Y.assert(x !== undefined) 
ReferenceError: Can't find variable: x 

这给我留下了

Y.assert(typeof(x) !== "undefined") // the only working option I've found 
Assert Error: Assertion failed. 

Y.Assert.isNotUndefined(x) 

同样可读少多了,我问:隐而不宣这不会破坏这些功能的目的,或者说我误解了框架?

所以

x 

是未申报的,所以不能直接检验的,而

var x; 

声明它,但它留下未定义。最后

var x = function() {}; 

既是声明和定义。

我觉得缺少了什么对我来说是很容易说

Y.Assert.isNotUndeclared(x); 

-Wil

+0

显示代码,因此ReferenceError中没有`x`中的变量。 – 2011-01-09 09:58:06

回答

0

背景:我希望能够之间的区别:

x // undeclared && undefined 
var x; // declared && undefined 
var x = 5; // declared && defined 

所以,这里的挑战是,JavaScript不容易区分前两种情况,我希望能够为教学目的做。大量的游戏和阅读之后,似乎是一个办法做到这一点,至少在网络浏览器的背景和全局变量(不是很大的限制,但...):

function isDeclared(objName) { 
    return (window.hasOwnProperty(objName)) ? true : false; 
} 

function isDefined(objName) { 
    return (isDeclared(objName) && ("undefined" !== typeof eval(objName))) ? true : false; 
} 

我意识到eval的使用可能是不安全的,但是对于我将使用这些函数的严格控制的上下文来说,它是可以的。所有其他人,请注意并参阅http://www.jslint.com/lint.html

isDeclared("x") // false 
isDefined("x") // false 

var x; 
isDeclared("x") // true 
isDefined("x") // false 

var x = 5; 
isDeclared("x") // true 
isDefined("x") // true 
2

OK,就有点晚了昨天的能力想我理解你现在的问题,你想什么做的是检查一个变量是否被定义了,对吧?

要做到这一点的唯一方法是typeof x === 'undefined'

typeof运算符允许使用不存在的变量。

所以为了它的工作,你需要上面的表达式,并将其插入正常的true/false断言。

例如(没用过YUI3):

Y.Assert.isTrue(typeof x === 'undefined', "fail message"); // isUndefined 
Y.Assert.isFalse(typeof x === 'undefined', "fail message"); // isNotUndefined