Jea*_*eri 38 unit-testing dom-manipulation jasmine
我需要用jasmine对一些DOM操作函数进行单元测试(目前我在浏览器和Karma中运行我的测试)
我想知道这样做的最佳方法是什么?
例如,我可以模拟和存根窗口并记录对象并监视它们的一些功能.但这并不是一个简单的解决方案,所以这就是为什么我问这个问题!
或者是否有更好的方法(不使用茉莉花)来做到这一点?
非常感谢
小智 28
我一直在github上使用一个名为jasmine-jquery的 jasmine的有用添加项.
它允许您访问许多有用的额外匹配器函数,以断言jquery对象及其属性.
特别是到目前为止我发现有用的功能是在dom元素的属性上声明,并且监视诸如点击和提交之类的事件......
这是一个有点人为的例子...... :)
describe("An interactive page", function() {
it("'s text area should not contain any text before pressing the button", function() {
expect(Page.textArea).toBeEmpty();
});
it("should contain a text area div", function() {
expect(Page.textArea).toBe('div#textArea');
});
it("should append a div containing a random string to the text area when clicking the button", function() {
var clickEvent = spyOnEvent('#addTextButton', 'click');
$('button#addTextButton').click();
expect('click').toHaveBeenTriggeredOn('#addTextButton');
expect(clickEvent).toHaveBeenTriggered();
expect($('div.addedText:last')).not.toBeEmpty());
});
});
Run Code Online (Sandbox Code Playgroud)
这是代码:
var Page = {
title : 'a title',
description : 'Some kind of description description',
textArea : $('div#textArea'),
addButton : $('button#addTextButton'),
init : function() {
var _this = this;
this.addButton.click(function(){
var randomString = _this.createRandomString();
_this.addTextToPage(randomString);
});
},
addTextToPage : function( text ) {
var textDivToAdd = $('<div>').html('<p>'+text+'</p>');
this.textArea.append( textDivToAdd );
},
createRandomString : function() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
},
};
Page.init();
Run Code Online (Sandbox Code Playgroud)
我发现茉莉是非常灵活的,并且到目前为止都很适合使用,我总是很感激指针使它成为更好的代码!