我需要使用Jasmine对一些DOM操作函数进行单元测试(目前我在浏览器和Karma中运行我的测试)
我想知道最好的方法是什么?
例如,我可以模拟和替换window和document对象,并监视它们的一些函数。但这似乎不是一个简单的解决方案,所以我才会问这个问题!
或者有更好的方法(也许不使用Jasmine)来实现这个?
非常感谢
我需要使用Jasmine对一些DOM操作函数进行单元测试(目前我在浏览器和Karma中运行我的测试)
我想知道最好的方法是什么?
例如,我可以模拟和替换window和document对象,并监视它们的一些函数。但这似乎不是一个简单的解决方案,所以我才会问这个问题!
或者有更好的方法(也许不使用Jasmine)来实现这个?
非常感谢
我一直在使用一个叫做jasmine-jquery的有用补充工具,它可以在Github上获得。
这个工具为你提供了许多实用的额外匹配器函数,可以断言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());
});
});
这里是代码:
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();
到目前为止,我发现茉莉花非常灵活且易于使用,但我总是感激那些可以帮助改进代码的提示!