Jasmine.js v2.0.0 - TypeError: Cannot read property 'stopPropagation' of undefined

KumarA picture KumarA · May 19, 2014 · Viewed 10.1k times · Source

I am new to Jasmine2 JS framework. I am using Jasmine.js framework to create test suites for my application developed in Backbone.js framework.

When I am creating test cases for Backbone.js -> views home.js file, one of my home.js views function has

event.stopPropagation();

and another function has

event.preventDefault();

If my Backbone.js -> views function has event.stopPropagation(); and event.preventDefault();, my test suites throws error as below:

TypeError: Cannot read property 'stopPropagation' of undefined

Please help me, how to write a test cases for my views function which has event.stopPropagation(); and event.preventDefault();

or

how to skip these has event.stopPropagation(); and event.preventDefault(); when I am calling function from Jasmine.js framework?

Kindly let me know, If you need any further clarification from my transition.

Thanks in advance.

Answer

user3428816 picture user3428816 · May 19, 2014

You can try this code, I hope this works for you to test events:

            var event = {
                type: 'click',
                stopPropagation: function () {},
                preventDefault: function () {}
            };          
            var stopPropagationSpy  = spyOn(event, 'stopPropagation');
            var preventDefaultSpy   = spyOn(event, 'preventDefault');           
            {OBJ}.{FUNCTION_TO_CALL}(event);
            $("{YOUR_ELEMENT_TO_TRIGGER}").trigger(event);
            expect(stopPropagationSpy).toHaveBeenCalledWith();
            expect(preventDefaultSpy).toHaveBeenCalledWith();