I have a nodejs application which has the client-side code build with backbonejs and requirejs. I want to test the client-side code on my nodejs server using mocha.
My mocha test file: test/view.coffee
requirejs = require 'requirejs'
global.define = requirejs
requirejs.config
nodeRequire: require
baseUrl: '../public/javascripts/libs/'
paths:
jquery: "jquery"
Underscore: "underscore"
Backbone: "backbone"
shim:
'jquery':
exports: '$'
'Underscore':
exports: '_'
'Backbone':
deps: ['jquery', 'Underscore']
exports: 'Backbone'
requirejs ['../public/javascripts/views/test_view'], (TestView) ->
describe 'TestView', ->
view = new TestView()
The Backbonejs file to be tested: public/javascripts/views/test_view.coffee
define [
'Backbone'
], (Backbone) ->
class TestView extends Backbone.View
initialize: ->
...
TestView
In public/javascripts/libs I have the minified (not AMD) versions of jquery, backbone, and underscore.
When I run my test I get the following error message:
Error: Calling node's require("../public/javascripts/views/test_view")
failed with error: Error: Calling node's require("Underscore")
failed with error: Error: Cannot find module 'Underscore'
at /node_modules/requirejs/bin/r.js:2262:27
Somehow the paths attribute of requirejs.config in test/view.coffee is not read. If I remove Backbone: "backbone" from paths, I dont't get an error message that the module 'Backbone' is missing. I didn't install Backbone and Underscore on the nodejs server.
Edit: Fixed the problem with the path by changing requirejs.config baseUrl to 'public/javascripts/views/test_view'. Requirejs is not using the path of the file (test/view.coffee) for the baseUrl block. For the requirejs ['...'], (TestView) part I have to use the path of the test/view.coffee file.
When I run my test with mocha I get the following error:
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Calling node's require("../public/javascripts/views/test_view")
failed with error: TypeError: Object #<Object> has no method 'load'
Edit: I forgot to mention that I've added 'jade!templates/test_template' to my test_view. I removed it, and now mocha is running the test. But I get the error:
TypeError: object is not a function
at Object.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native)
the line:
view = new TestView()
is causing the error.
The issue here is that on the server, RequireJS falls back to node's require(). A possible solution would be to install Backbone with NPM, and symlink node_modules/backbone/backbone.js to public/lib/backbone.js. You could then require backbone using either node's or RequireJS' require().