gpt4 book ai didi

javascript - 我如何使用 Sinon stub $(window).width() ?

转载 作者:数据小太阳 更新时间:2023-10-29 05:15:14 24 4
gpt4 key购买 nike

我在 JS View 中有一个函数,如果窗口宽度小于 1000,它会执行一些操作。我正在尝试使用 Mocha、chai 为此编写单元测试,并通过 Phantom/Chrome/中的 karma 测试运行器运行测试Chromium 浏览器。

我还使用 sinon 对方法进行 stub 并使其返回一些所需的值。现在有一个条件检查,如果窗口宽度小于 1000,那么我怎么能 stub 呢,我正在尝试类似下面的方法,

sinon.stub($(window).width());
$(window).width().returns(900);

但它不起作用。有什么特定的方法可以 stub $(window).width() 值吗?

最佳答案

sinon.stub() 用法:

首先:您没有正确地将方法/函数传递给 sinon.stub()。正确的做法是:

sinon.stub(object, 'method');

其中 object 是一个对象,其方法要 stub ,'method' 是一个包含此方法名称的字符串。

另一种方法是简单地用 stub 覆盖当前函数,调用不带参数的.stub():

object.method = sinon.stub();

考虑到这一点,让我们继续处理您当前的代码。

当前代码:

sinon.stub($(window).width());

正如我上面所写 - 这是对 sinon.stub() 的错误调用。

撇开这一点不谈,您是从错误的 Angular 接近它。你不能 stub $(window).width() - $(window).width() 不是一个函数,它是一个调用到一个函数 - 返回一个数字(此处:窗口的宽度,以 px 为单位)。 这就是您实际尝试用 stub 替换的值 - 任意基元(数字),甚至没有绑定(bind)到任何变量。

下一步尝试:

sinon.stub($(window), 'width');

现在,为什么不起作用

我们只是在这个特定 jQuery 对象上 stub width 方法 - 但是每次调用 $(...) 创建一个新的。结果如下:

var $window = $(window);
sinon.stub($window, 'width').returns(900);

$window.width(); // 900 - using .width() method stub
$(window).width(); // real window width - new jQuery object

(jsfiddle:http://jsfiddle.net/xqco8u77/)

解决方案

在 jQuery 对象的 prototype 上存入 .width() 方法 - 每个 jQuery 对象的方法/值在全局范围内可用。

sinon.stub($.prototype, 'width').returns(900);

// "900"
$(window).width();

// restoring original function
$.prototype.width.restore();

// real window width
$(window).width();

jsfiddle 上的工作演示:http://jsfiddle.net/gjcguvzh/5/

(如您所见,在使用 stub 后,我还恢复了原始的 .width() 原型(prototype)方法,以防您以后需要使用它。)

关于javascript - 我如何使用 Sinon stub $(window).width() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30627490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com