1

Backbone.js is working fine when I compile it with browserify, however I'm having a hard time testing my Backbone.Model's under Mocha. When I do I get,

TypeError: Cannot read property 'apply' of undefined
  at Object.Backbone.ajax (/node_modules/backbone/backbone.js:1409:27)

backbone.js, line 1409 has,

return Backbone.$.ajax.apply(Backbone.$, arguments);

So, Backbone.$ isn't being defined.. Thing is I'm using node/CommonJS and clearly (trying) to set it... Again, this works under browserify,

var Backbone = require('backbone');
Backbone.$ = require('jquery);

I can see others have had this problem too by searching the forums. Maybe running jQuery in node is impossible? I tried it from the node REPL shell..

var $ = require('jquery'); $.ajax();
TypeError: $.ajax is not a function

And, something new...

var $ = require('jquery')(global); $.ajax();
Error: jQuery requires a window with a document

Still no joy.. Any ideas?

  1. How do I get my Backbone.Model's .save (which delegates to jQuery) to run outside of browserify, and in node under Mocha?
  2. Can I do this transparently using the same source Backbone.Model under both Mocha test suite and the browser?
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468
  • I'd say jQuery within NodeJS is 1) overkill (unless your NodeJS application is using jQuery - but I'd say this is not the case) 2) IMO unwanted when testing. Since you want to test a Model you could even mock away `sync()` (when testing everything else) or when you're testing `sync()`, define `Backbone.$` with a simple mock-jQuery object just providing `ajax()` to satisfy the test dependencies. Then you can easily that how your mock `ajax()` has been called. – try-catch-finally May 28 '15 at 21:04

0 Answers0