是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)
答案 0 :(得分:1)
最后设法让它发挥作用。
首先,我开始使用jasmine-jquery库来使用html
加载setFixtures
,因为要jquery click
工作,首先需要获取jquery selector
的实例。
然后我spyOn
使用
modal
spyOn($.fn, "modal");
所有spying
的差异应该仅在beforeEach
由于某种原因发生,如果在真实测试中它不起作用(不确定原因)。
然后在按钮上使用jquery
,click
。
$('#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();
});
})