My goal is to use one language and share logic across two environments, the server and the browser. I want to do this easily.
Update (2015-01-21): I no longer use RequireJS. I now use and recommend Browserify to share logic across the server and browser.
Why CommonJS didn’t work in the browser
RequireJS in the browser
RequireJS has allowed me to share logic across node and the browser. I believe it was written with this idea in mind. If RequireJS can’t find a module dependency in my project code, it will search through Node’s node_module directory for the dependency. This functionality ties in to Node’s large library of NPM modules. I can include NPM modules in my browser bundle too, which increases the browser side library selection. So far, I am happy with RequireJS.
Testing with Mocha
I use Sinon for test spies. These “spies” double as delegate objects and watch calls made to them (or not made to them). I can later inspect the spy object and verify that certain calls were made. I can check the arguments passed and the number of times a method is called.
I use Chai for my assertion library. It allows me to say things like
chai.assert.equal(a, "test text string"); These tests are used to verify my expectations about an implementation that I am testing.
Automating with Karma
I want my tests to be run without me putting much effort in. I want to be editing code and when I save, tests get run and my logic is tested. To do that I use Karma in the browser environment and Mocha’s test runner api in the server (Node) environment. I can write a single test and it can be run in both environments. Right away I’ll know if something isn’t working in one environment or the other. It is a proof of the cross platform design of my code and of the particular logic I am testing.