测试jquery点击回拨

时间:2014-04-08 14:17:00

标签: javascript angularjs unit-testing testing jasmine

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)

1 个答案:

答案 0 :(得分:1)

最后设法让它发挥作用。 首先,我开始使用jasmine-jquery库来使用html加载setFixtures,因为要jquery click工作,首先需要获取jquery selector的实例。

然后我spyOn使用

modal
spyOn($.fn, "modal");

所有spying的差异应该仅在beforeEach由于某种原因发生,如果在真实测试中它不起作用(不确定原因)。

然后在按钮上使用jqueryclick

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

最后expect上的spied 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();
  });
})