1

Am a newbie in jasmine, trying to test the jquery click call back function

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

My test code is

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

But am getting the below when I execute the test

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 Answer 1

1

Finally managed to make it work. First i started to use jasmine-jquery library to load the html using setFixtures because for the jquery click to work it needs to first get an instance of the jquery selector.

Then i spyOn on the modal using

spyOn($.fn, "modal");

The difference being all spying should happen only on beforeEach for some reason, if inside the real test its not working (not sure why).

Then using jquery, click on the button.

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

Then finally expect on the spied modal.

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

Finally

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

The Test:

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();
  });
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.