Reputation: 4970
I have been trying to integrate unit testing with my Backbone models through an express node.js project, and having difficulties grasping exactly how to accomplish this task. (sidenote: I come from a lot of Java background, and I realize there are differences, but I am loving the simplicity and elegance of the node development environment so far.)
My problem stems from the following issue, backbone models need to be exposed to the browser in order to run within it, whereas testing through mocha is "server side" on the node runtime environment.
Here is an example of what I am talking about:
Model File: /public/js/backbone/models.js
var SomeModel = Backbone.Model.extend({...});
Server Side Test: /test/backbone/models-test.js
???
I write ??? because normal unit testing via server side you just do:
var SomeModule = require('./someModule');
and go about your merry way. Obviously, since the browser is not running within Node, modules aren't readily available.
I have read some posts stating you need to wrap your browser-side javascript within require.js which will put those javascript files into the node namespace automagically allowing you to do a require and go on with your testing. However, I have not found a coherent way of accomplishing such a task, and I have tried searching around for examples, but can't seem to find something that applies. Granted, it very well might be my general lack of knowledge for this framework since I'm still wrapping my head around the entire idea of how things are scoped in javascript, injection of dependencies, etc.
Any help would be much appreciated, and I apologize if this question has been asked a million times already, I'm sure it has, and I'm asking it in an incorrect way.
Thanks in advance.
Upvotes: 0
Views: 1136
Reputation: 146064
If you have some node-only code (like your unit tests if you only plan to execute them under node), you can take this approach:
var Backbone = require('backbone');
public/js/backbone.js
to the file under node_moules/backbone/backbone.js
if you like.If you have browser-only code, you can either use the Backbone
global variable or a require.js
shimmed version of it if you like.
If you have code (like your Models) that you want to run in the browser but also work in node, the cleanest solution is to code it CommonJS (node) style using var Backbone = require('backbone');
and run it that way in node, but wrap it with a requirejs/AMD wrapper when you send it to the browser and use require.config
& require.paths
to map 'backbone' to your backbone.js file.
Details in this very popular question/answer:
https://stackoverflow.com/a/10914666/266795
See also:
http://backbonetutorials.com/organizing-backbone-using-modules/
Upvotes: 5