我有一些代码,如下所示:
var x = x || (function() {
// Some private variables
// ...
return {
init:function(options) {
// Do stuff
// ...
},
// Some other public methods
// ...
};
})();
如果我是正确的,那么这是一个单例类。现在我想使用 Jasmine 为这个类编写一些单元测试。我从这样的事情开始:
describe("x", function() {
var myX;
beforeEach(function(){
myX = x;
});
it("has been instatiated correctly", function() {
expect(myX.init).toBeDefined();
});
});
我了解到,由于最外面的 function(){}
周围有括号,因此该单例被实例化 immediately after it has been parsed.代码的其余部分中缺少对此单例的 init
方法的调用,这强化了我的假设(在这种情况下 init
方法的意义是什么?)。
由此得出结论,我知道
var myX;
beforeEach(function(){
myX = x;
});
不可能是对的。我已经尝试了许多其他排列来获得一些可以使用的东西(从将其全部排除开始,因为我认为当浏览器达到测试规范时,包含代码的文件已经被解析,因此单例类应该有空,对吧?)。但一切都会导致完全相同的错误消息:
ReferenceError: x is not defined
那么我该如何解决这个问题呢?
提前致谢!
——克里斯
最佳答案
If you get x is not defined, you seem not to have included the module code. Please show us how you embed it in your tests.
使用两种类型断言(一种在实例化之前,一种在实例化之后)来测试单例:
function foo()
{
foo = {};
return 1;
}
console.assert(foo.constructor === Object, "foo.constructor === Function", 'foo should be a type of Function before it is instantiated')
foo();
console.assert(foo.constructor === Object, "foo.constructor === Object", 'foo should be a type of Object after it is instantiated')
引用文献
关于javascript - 我应该如何使用 Jasmine 在 JavaScript 中对单例进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15383009/