gpt4 book ai didi

javascript - 如何使用 Jasmine 测试我的 Javascript 回调?

转载 作者:行者123 更新时间:2023-11-28 08:30:06 25 4
gpt4 key购买 nike

我需要测试当用户将窗口滚动到某个点时是否调用特定方法。在我的源代码中,我附加了 Windows 监听器,例如:

$(window).on("scroll.singleJob",function(e)
{
// code here, check if the window is scrolled past certain point etc. and then I need to call this method
LozengesPanel.makeFixed();
}

现在,在我的 Jasmine 测试中,我试图确认当窗口滚动到某个点时正在调用该方法。所以我设置了测试:

describe("SingleJob page", function() {

beforeEach(function() {

loadFixtures('my_fixture.html');
});


it("panel sticks to top when page scrolled down", function() {

spyOn(mycompany.singleJobTestable.LozengesPanel, "makeFixed");

window.scroll(0,1000);

expect(mycompany.singleJobTestable.LozengesPanel.makeFixed).toHaveBeenCalled();
});
});

但是测试失败了,我得到的只是预期 spy makeFixed 已被调用。如何触发窗口滚动以便我可以测试此回调内的方法?

编辑:

最后,这一切都有意义了。似乎滚动事件被放入任务队列中,仅在当前线程完成后才执行。添加 $(window).trigger("scroll");成功了。我发布了简短的博客文章来解释这个问题 http://spirytoos.blogspot.com.au/2014/02/testing-windowscroll-with-qunitjasmine.html

最佳答案

编辑:这个答案不能满足问题。原因见评论。

实际上,您似乎正在触发 Jasmine 规范中的滚动事件。我尝试了非常相似的代码,我将其包含在下面。但是,我的 expect 仍然失败,就像你的一样(我仍在熟悉 Jasmine,所以我无法确定地解释为什么会这样)。

var fun = {
scrollEventCallback: function() {
console.log('scroll event triggered');
}
};
$(window).on('scroll', fun.scrollEventCallback);

describe("A test suite", function() {

it("should trigger f", function() {
spyOn(fun, "scrollEventCallback");
$(window).trigger('scroll'); // my callback function is executed because it logs to the console
expect(fun.scrollEventCallback).toHaveBeenCalled(); // this fails anyway
});
});

关于javascript - 如何使用 Jasmine 测试我的 Javascript 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21975578/

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