Fake xmlhttprequests using casperjs

I am writing end-to-end tests using casperjs and would like to fake ajax server responses

I had the idea to include a simple script that mocks the xmlhttprequest object and will always return my expected results, for example the following

var ajax_requests = [ ['GET', '/jobs', JSON.stringify(jobs)] ], stubs = stubs || {}; function setup_ajax(){ stubs.server = sinon.fakeServer.create(); _.each(ajax_requests, function(r){ //r[1] = "http://localhost:8000" + r[1] r[2] = [200, { "Content-Type": "application/json" }, r[2]] stubs.server.respondWith.apply(stubs.server, r) }) stubs.server.autoRespond = true; stubs.server.autoRespondAfter = 2; } 

Then I call setup_ajax in my cache testing, like

 casper.then(function(){ this.evaluate(setup_ajax) } 

but seemingly future ajax requests still avoid the implementation of xmlhttprequest.

I tried running setup_ajax on the fly using $ .ready () and calling it from casper too, but none of them worked

More interestingly, checking for the existence of objects strangely fails.

 function setup_ajax(){ return typeof(sinon) } casper.then(function(){ var x = this.evaluate(setup_ajax) casper.log(x) // logs 'null' } 

But the sine is correctly turned on, at least the random case did not cause errors when I made some calls to it outside the setup_ajax function, but it caused an error when I deliberately excluded the sine.

Do you have any ideas about bullying xmlhttprequests under casperjs?

+4
source share
2 answers

You can use sinon.js to fake XmlHttpRequest.

+4
source

PhantomXHR wraps XHR with a mock SinonJS for casperjs.

First you need to initialize PhantomXHR:

 var xhr = require('phantomxhr'); casper.on('page.initialized', function () { xhr.init(casper.page, { libraryRoot: '/path/to/node_modules/phantomxhr/' }); }); 

How can you fake an XHR request:

 var fake = xhr.fake({ url: '/jobs', responseBody: jobs }); 

Make sure the XHR request completes before evaluating the page. You can check if the request is completed by searching

 fake.count() === 1 
+1
source

All Articles