1

I have the following method in my controller:

$scope.onWindowResize = function() {
    var dWidth= $('#div1').width();
    var left = $('#div1').position().left;
    $('.myClass1').css({'width':dWdth});
    $('.myClass2').css({'left': left});
}

I am trying to test the method onWindowResize() with the below code.

it('onWindowResize()', inject(function () {
    scope.onWindowResize();
    scope.$apply();
}));

But I get this error message:

"message": "'undefined' is not an object (evaluating '$('#div1').position().left')"

and

dWidth is null

I have sinon spy, but not sure how to use it here. Can I use it somehow to spy on it, or is there a better way to test this method? I think I need to mock "$('#div1')", but no idea how to do that. Any help is highly appreciated.

  • Possible duplicate of [Jasmine mock chained methods with Karma and Angular](http://stackoverflow.com/questions/36285896/jasmine-mock-chained-methods-with-karma-and-angular) – Estus Flask Dec 27 '16 at 16:26
  • Basically the entire `$('#div1').position().left` chain should be recreated as a stub. – Estus Flask Dec 27 '16 at 16:28

1 Answers1

0

First, there is typo in your code, you're using dWidth wrong in css function like this adjWdth. You can create a spy on $ / jQuery function like this and spy for css function

var cssSpy = jasmine.createSpy('cssSpy');
$ = jasmine.createSpy().andCallFake(function(){
    return {
        width:function(){return 200;},
        position: function(){return{left:500};},
        css: cssSpy
    };
});
$scope.onWindowResize();
expect(cssSpy).toHaveBeenCalledWith({'width':200});
expect(cssSpy).toHaveBeenCalledWith({'left':500});

As you can see, I'm overwriting $ / jQuery function itself and returning an object with the properties/methods you use in the onWindowResize function. And also a spy for css function. andCallFake is old version of jasmine the new one is .and.callFake(). Please confirm if it works for you and study it well. You can do it in beforeEach block to be reusable and mock all keys you want to return when you selecting a DOM element ;). By the way, it's not recommended to have a DOM manipulation code inside controller, it should be in a directive's link function.

tanmay
  • 7,761
  • 2
  • 19
  • 38
Mohammed Ramadan
  • 655
  • 7
  • 10