VladJS
VladJS

Reputation: 191

How to mock jquery ajax call while testing angular page

I'm writing e2e test for my angular page with protractor. I use $httpBackend for mocking requests which are sent by $http But in one old page i found jquery ajaxFrom plugin which sends call by jquery ajax. I noticed that it couldn't be mocked by $httpBackend

What is the best solution for mocking this stuff?

Upvotes: 2

Views: 784

Answers (1)

VladJS
VladJS

Reputation: 191

After investigation I found quite simple way to handle jquery ajax calls from angular page (which is made by jquery ajaxForm plugin) In our test spec i just put

browser.executeScript( '$.fn.ajaxForm = function(form){return{submit: function(){form.success([{result: "ok"}]);}}}' );

So in this way i mocked request that is being sent by jquery ajaxForm plugin.

Also in same way we can mock native JS XMLHTTPRequest object

            window.XMLHttpRequest = function(){
                return{
                    send: function(){return true;},
                    open: function(){return true;},
                    status: 200,
                    responseText: '{result: "ok"}',
                    getAllResponseHeaders: function(){return true;},
                    readyState: 4
                }
            }

Upvotes: 3

Related Questions