我想用QUnit和Sinon.Js编写单元测试。我有一个应用程序,用户可以点击按钮和模式对话框来处理下载一些文件。用户可以关闭对话框,它会触发一个方法来运行以重置某些变量。我的测试代码:
$(function() {
$.fn.copy_button = function(){};
ln_download_view = new DownloadModalView();
ln_download_view.modal = {'modal': function() {}};
var download_modal_dialog = $('.download-modal');
download_modal_dialog.modal = function(param){};
var modal_mock = sinon.mock(ln_download_view.modal);
var download_modal_dialog_mock = sinon.mock(download_modal_dialog);
//Should be inserted, because ln_download_view.modal is mocked
//The close button even handler
$('#btn_close_modal').click(function(){
download_modal_dialog.modal('hide');
});
//Dirty stuff to do after the window closes
//Basicly the click triggers this event handler
$('.download-modal').on('hide',function() {
window.clearInterval(window.periodicalTimer);
});
$('div .option-container').click(function() {
if(!$(this).hasClass("selected-option"))
{
$('div #option-presenting').toggleClass("selected-option");
$('div #option-editing-and-presenting').toggleClass("selected-option");
$('.image').toggle();
}
});
module("views");
test("Download modal dialog is displayed", function(){
var modal_triggered = modal_mock.expects("modal").once();
ln_download_view.handleDownloadClick();
ok(modal_triggered.verify());
});
test("Download modal dialog is closed",function(){
var modal_triggered = download_modal_dialog_mock.expects("modal");
$('#btn_close_modal').trigger('click');
ok(modal_triggered.verify());
});
});
我不明白的是,我如何测试/模拟/存储这段代码:
$('.download-modal').on('hide',function() {
window.clearInterval(window.periodicalTimer);
});
我还没有深刻的了解。
答案 0 :(得分:5)
您无法模拟/存根匿名函数。但是你可以进行重构并存根/模拟命名的回调。
$('.download-modal').on('hide', onHide);
var onHide = function() {
window.clearInterval(window.periodicalTimer);
};
// ...
sinon.stub(onHide);
答案 1 :(得分:2)
这是我的方法:
在每个人面前,制作一个不做任何事情的功能:
var doNothing = function(){};
然后在你的测试中,窥探:
var spy = sinon.spy(this, 'doNothing');
然后调用你的方法,传入一个触发doNothing方法的回调:
var self = this;
whatever.doSomethingAwesome(
{
finished: function(){
self.doNothing();
}
});
expect(spy.callCount).toEqual(1);