pub*_*orn 2 window maven jasmine
为了增加项目的测试覆盖率,我开始为现有的JS代码构建测试.
其中一个现有模块使用jQuery将窗口高度放在一个变量中:var window_height = jQuery(window).height(); 内部jQuery使用clientHeight属性.
现在使用mvn clean install或mvn -o test我收到错误: 无法从null读取属性"clientHeight"
我假设这是因为Jasmine创建的"虚拟浏览器"没有window属性.有没有办法让这项工作?
我不能保证覆盖jQuery方法的安全性,但是这里你可以使用jasmine的spyOn函数来覆盖$(window).height()返回的内容.
it("can override jquerys height function", function() {
var original = $.prototype.height;
spyOn($.prototype, 'height').andCallFake(function() {
if (this[0] === window) {
return 5; // whatever you want the window height to appear to be
} else {
return original.apply(this, arguments);
}
});
// window height gets overridden
expect($(window).height()).toEqual(5);
// everything else uses the actual jQuery call
expect($("body").height()).toBeGreaterThan(5);
});
Run Code Online (Sandbox Code Playgroud)
或者,在某处创建自己的getWindowHeight()函数会更安全spyOn.
| 归档时间: |
|
| 查看次数: |
2028 次 |
| 最近记录: |