【问题标题】:how to unit test DOM manipulation (with jasmine)如何对 DOM 操作进行单元测试(使用 jasmine)
【发布时间】:2013-04-16 08:14:13
【问题描述】:

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

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

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

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

非常感谢

【问题讨论】:

标签: unit-testing jasmine dom-manipulation


【解决方案1】:

我一直在对 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 非常灵活且易于使用,但我一直很感激那些让代码变得更好的指针!

【讨论】:

  • 对于 DOM 操作,我不使用 jQuery。我想那是个问题?
  • 我想应该没问题 - 这里的 jQuery 可能只用于获取元素;一般来说,所有这些库都只是在底层进行相同类型的 DOM 操作。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2021-01-28
    • 2017-02-28
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多