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

标签 javascript unit-testing jasmine

我需要测试当用户将窗口滚动到某个点时是否调用特定方法。在我的源代码中,我附加了 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/

相关文章:

objective-c - 使用 XCode 3 对 iPhone 静态库进行单元测试

delphi - 如何在 PascalMock 中模拟具有开放数组参数的方法?

typescript /karma : Making CommonJS available to Karma during test runs

selenium - 使用 Javascript 进行敏捷开发

javascript - 为什么 JavaScript 语句 "ga = ga || []"有效?

javascript - 查找数字的第 n 位 JavaScript

.net - 未在使用Microsoft Fakes的C#测试项目中的/reference选项“/引用选项”中指定错误 "The extern alias ' snh'

javascript - 访问包装在高阶组件中的组件中的实例方法 - React.js

javascript - JS - 数组的总和列表(文本字段中的总和名称)

javascript - Chrome 扩展(内容脚本)- 在字符串中的特定位置添加按钮