【问题标题】:Testing jquery click call back测试jquery点击回调
【发布时间】:2014-04-08 14:17:00
【问题描述】:

我是jasmine的新手,正在尝试测试jquery click的回调函数

$('#upload-btn').click(function(){
    $("#myModal").modal('show');
});

我的测试代码是

describe('upload button attaches to modal', function(){
    it('attaches successfully', inject(function($controller, $httpBackend) {
        spyOn($.fn, "click");
        spyOn($.fn, "modal");
        $httpBackend.expectGET('service/search/populate/procedureNumberList');
        var scope = {}, ctrl = $controller('uploadARController', {
            $scope : scope
        });
        $httpBackend.flush();
        expect($('#upload-btn').click).toHaveBeenCalledWith(jasmine.any(Function));
        $('#upload-btn').click();
        expect($.fn.modal).toHaveBeenCalled() <<<---- Failing here;
    }));
})

但是当我执行测试时得到以下结果

PhantomJS 1.9.7 (Windows 7) Upload AR Test upload button attaches to modal attaches successfully FAILED
        Expected spy modal to have been called.
PhantomJS 1.9.7 (Windows 7): Executed 3 of 3 (1 FAILED) (0.165 secs / 0.026 secs)

【问题讨论】:

    标签: javascript angularjs unit-testing testing jasmine


    【解决方案1】:

    终于成功了。 首先,我开始使用jasmine-jquery 库来使用setFixtures 加载html,因为要使jquery click 工作,它需要首先获取jquery selector 的实例。

    然后我在modal 上使用spyOn

    spyOn($.fn, "modal");
    

    由于某种原因,所有spying 的区别应该只发生在beforeEach 上,如果在实际测试中它不起作用(不知道为什么)。

    然后在按钮上使用jqueryclick

    $('#upload-btn').click();
    

    最后是expectspied modal

    expect($("#myModal").modal).toHaveBeenCalled();
    

    终于

    beforeEach(inject(function($httpBackend) {
     setFixtures('<button class="btn btn-default" type="button" id="upload-btn" >Upload</button>');
     spyOn($.fn, 'modal');
    }));
    

    测试:

    describe('upload button attaches to modal', function(){
      it('attaches successfully', function() {
        inject(function($controller){
         var scope = {}, ctr = $controller('uploadARController', {$scope:scope});
        });
        $('#upload-btn').click();
        expect($("#myModal").modal).toHaveBeenCalled();
      });
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-24
      • 2023-04-10
      相关资源
      最近更新 更多