我正在编写一个关于 Range 对象的测试。我的代码类似于以下内容。
Test = function () {};
Test.prototype.test = function () {
if (window.getSelection) {
var sel = window.getSelection();
var range = sel.getRangeAt(0);
// then some code;
} else if (document.selection) {
range = document.selection.createRange();
//then some code;
return 'haha';
}
it('should create range object', function () {
var myTest, result;
myTest = new Test();
spyOn(myTest, 'test').andReturn('haha');
result = myTest.test();
expect(result).toEqual('haha');
});
当我运行测试时,它抛出一个错误:INDEX_SIZE_ERR: INDEX_SIZE_ERR: DOM Exception 1
但是我的代码在浏览器中运行良好。
然后我发现了一些关于getRangeAt的信息和 rangeCount .
Before the user has clicked a freshly loaded page, the rangeCount is 0.
然后我尝试添加像 $(document).click();
这样的代码,rangeCount 仍然是 0...
它仍然抛出INDEX_SIZE_ERR: INDEX_SIZE_ERR: DOM Exception 1
那么,问题是:如何在 jasmine 中正常测试 Range 对象?
最佳答案
你必须模拟window.getSelection
或document.selection.createRange
,这样原始方法就不会被调用。
it('should create range object', function () {
var myTest, result;
myTest = new Test();
//mock the select function so that it will return "haha" when getRangeAt is called
var range = 'haha';
var rangeObject = {
getRangeAt: function(){return range}
};
spyOn(window, 'getSelection').andReturn(rangeObject)
spyOn(myTest, 'test').andReturn('haha');
result = myTest.test();
expect(result).toEqual('haha');
});
关于javascript - 如何测试 Jasmine 中的范围对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18544384/