我一直在对 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();
到目前为止,我发现 jasmine 非常灵活且易于使用,但我一直很感激那些让代码变得更好的指针!