Having trouble with jQuery ajax calls #440

Closed
maraujop opened this Issue May 29, 2012 · 5 comments

Projects

None yet

3 participants

@maraujop

Hi there,

I'm new to mocha.js and I started doing a test for a very simple Backbone model. Within the test I create the model and I do model.fetch. error callback is getting called with a response object that contains statusText: 'No Transport'. So my understanding is that my ajax call is being considered cross site, so jQuery doesn't really send it, but dismisses it for security reasons.

I would like to run mocha asynchronous calls against a test server (http://127.0.0.1:8000), running my real API, with fixtures loaded. That before using any mocking library like sinon. I've tried the old trick of setting jQuery.support.cors = true;, but doesn't work.

is this possible? am I doing something wrong? Sorry I have very basic node.js knowledge to try to fix this myself.

Thanks, cheers
Miguel

@maraujop

To be more precise. If I set jQuery.support.cors = true; or set a localContext in node.js to avoid cross-site scripting.

I get statusText: 'TypeError: Object #<XMLHttpRequest> has no method \'open\''

Cheers,
Miguel

@tj
tj commented May 29, 2012

that's something wrong with backbone or your jquery usage, mocha doesn't touch a single thing in jquery. As far as jquery's API for cors stuff I have no clue

@tj tj closed this May 29, 2012
@maraujop

Thanks @visionmedia, I've finally found what was going on.

For other people that find themselves with the same issue, this is how to set jQuery so that its ajax calls work in nodejs + mocha.

  • Basically we need $.support.cors set to true, for fixing cross site
  • Then set $.ajaxSettings.xhr to use xmlhttprequest (this needs npm install xmlhttprequest).
$ = require('jquery');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
$.support.cors = true;
$.ajaxSettings.xhr = function () {
    return new XMLHttpRequest;
}

var _ = require('underscore')
var Backbone = require('backbone')
Backbone.setDomLibrary($);

This fixes the issue, now mocha is doing requests against my real testing server.

Cheers,
Miguel

@ndnichols

Thanks @maraujop, this worked great for me.

Best,
Nate

@maraujop

You are welcome Nate, glad it helped you :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment