41

我需要用 jasmine 对一些 DOM 操作函数进行单元测试(目前我在浏览器和 Karma 中运行我的测试)

我想知道最好的方法是什么?

例如,我可以模拟和存根窗口文档对象并监视它们的几个函数。但这看起来并不是一个简单的解决方案,所以这就是我问这个问题的原因!

还是有更好的方法(也许不使用茉莉花)来做到这一点?

非常感谢

4

2 回答 2

29

我一直在使用 jasmine 的一个有用的补充,称为github 上的 jasmine-jquery 。

它使您可以访问许多有用的额外匹配器函数,以断言 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 非常灵活且易于使用,但我总是很感激那些让代码变得更好的指针!

于 2013-04-23T16:16:01.790 回答
3

我一直在为自己寻找一些东西,最后我用 19 个自定义匹配器创建了一个小库。也许你会发现它很有帮助。 https://github.com/devrafalko/jasmine-DOM-custom-matchers

于 2016-12-12T17:26:58.790 回答