【问题标题】:testing for click event with jasmine?用茉莉花测试点击事件?
【发布时间】:2018-02-19 19:23:06
【问题描述】:

我需要编写一个 Jasmine.js 测试来测试菜单图标在单击时会发生什么,(第一次单击时菜单栏滑入,单击时滑出第二次这样做,但我的测试未能证明)

我提出了这个想法,但规范运行程序显示(预期错误为真)。关于可能是什么问题的任何帮助?

describe('The menu', function () {
     /* TODO: Write a test that ensures the menu changes
      * visibility when the menu icon is clicked. This test
      * should have two expectations: does the menu display when
      * clicked and does it hide when clicked again.
      */

      it('the menu changes visibility when the menu icon is clicked', function () {

          var menuIconClicked, menuChangesWhenClicked = false, 
          menuChangesWhenClickedAgain = false;

          $(".menu-icon-link").click(function(){
            var $this = $(this);
            $(this).data('clicked', true);
            if($(this).data('clicked')) {
                menuIconClicked=true // if menu icon is clicked, set the menuIconClicked value to true
                 if (menuIconClicked && $('body').hasClass(null)) {
                    menuChangesWhenClicked=true;

          }
            }
            if($this.data('clicked') && menuIconClicked===true) { 
                menuIconClicked=false // if menu icon is clicked when it already has been clicked aka menuIconClicked===true
                if (!menuIconClicked && $('body').hasClass('menu-hidden')) {
                    menuChangesWhenClickedAgain=true;

          }
            }

        });
            expect(menuChangesWhenClicked).toBe(true);

            expect(menuChangesWhenClickedAgain).toBe(true);

      });

});

【问题讨论】:

标签: javascript jasmine automated-tests


【解决方案1】:

看起来您已经在使用 Jasmine 和 JQuery,所以我建议您也使用 jasmine-jquery.js 库来帮助您跟踪状态?

这是一个很好的参考:Testing That A DOM Event Was Fired

要使下面的代码正常工作,只需将 jasmine-jquery.js 包含在您的项目文件夹中,通过 index.html 的 和您的集合链接 。希望这可以帮助。

describe('The menu', function() {
    // Add a spyOnEvent
    let spyEvent, menu;

    beforeEach(function() {
        // I assumed your menu icon has a unique ID of 'menuIconID'
        // so I passed onto a spy listener.
        spyEvent = spyOnEvent('#menuIconID', 'click');
    });
    it('the menu changes visibility when the menu icon is clicked', function() {

        // Click once
        $("#menuIconID").trigger("click");
        expect('click').toHaveBeenTriggeredOn('#menuIconID');
        expect(spyEvent).toHaveBeenTriggered();
        menu = $('body').attr('class'); // assign the new class
        expect(menu).toBe('');

        // Click again
        $("#menuIconID").trigger("click");
        expect('click').toHaveBeenTriggeredOn('#menuIconID');
        expect(spyEvent).toHaveBeenTriggered();
        menu = $('body').attr('class'); // update the new class
        expect(menu).toBe('menu-hidden');
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    相关资源
    最近更新 更多