如何对DOM操作进行单元测试(使用jasmine) [英] how to unit test DOM manipulation (with jasmine)
问题描述
我需要使用jasmine对一些DOM操作函数进行单元测试(目前我在浏览器中使用Karma运行我的测试)
I need to unit test some DOM manipulation functions with jasmine (currently I run my tests in the browser and with Karma)
我想知道什么是最好的方法要做到这一点吗?
I was wondering what the best approach would be to do this ?
例如,我可以模拟并存根窗口和文档对象并窥探他们的几个功能。但这看起来并不是一个简单的解决方案,所以这就是为什么我会问这个问题!
For example, I can mock and stub the window and document objects and spyOn a couple of their functions. But this doesn't really look like an easy solution, so thats why I'm asking this question!
或者有更好的方法(不要使用茉莉花)这样做吗?
Or is there a better way (not using jasmine maybe) to do this ?
非常感谢
推荐答案
我去过在github上使用了一个名为 jasmine-jquery 的jasmine的有用添加内容。
I've been using a helpful addition to jasmine called jasmine-jquery available on github.
它允许您访问许多有用的额外匹配器函数,以断言jquery对象及其属性。
It gives you access to a number of useful extra matcher functions, to assert jquery objects and their properties.
特别是我有的功能到目前为止发现有用的是断言dom元素的属性,并监视点击和提交等事件......
In particular the features I have found useful so far are asserting on attributes of dom elements, and spying on events such as clicks and submits...
这是一个有点人为的例子...... :)
Here is a somewhat contrived example... :)
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();
我发现茉莉花非常灵活,并且到目前为止都很好用,我总是很感激指针尽管让代码变得更好!
I've found jasmine to be really flexible and agreeable to use so far, I always appreciate pointers for making it the code better though!
这篇关于如何对DOM操作进行单元测试(使用jasmine)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!