2014-04-08 65 views
1

我在jasmine一個新手,試圖測試了jQuery click回調函數測試jQuery的點擊回撥

$('#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

最後設法使它工作。 首先,我開始使用jasmine-jquery庫來使用setFixtures加載html,因爲要使jquery click正常工作,需要先獲取jquery selector的實例。

然後我spyOn使用

spyOn($.fn, "modal"); 

的區別是所有spying應該只發生在beforeEach出於某種原因,如果實際測試中它不工作的modal(不知道爲什麼)。

然後在按鈕上使用jquery,click

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

然後在spied modal終於expect

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(); 
    }); 
})