Search code examples
javascriptjquerybackbone.jsjasminejasmine-jquery

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


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

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?


Solution

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