Last Updated: February 25, 2016
· Tomás Prado

Test a requirejs project using mocha-phantomjs, chai and sinon

I was trying this week to configure and test a requirejs project. It uses mocha-phantomjs to execute the tests; chai as the assertion library; and sinon.js to mock or stub dependencies.

I tried this how-to test requirejs with mocha-phantomjs and grunt , but didn't get enough info about how to add chai and sinon.

I finally conclude that the best and easiest way to accomplish that is like this:

  • sinon.js included in a script tag in the testRunner.html
  • chai.js included in the asynchronous module definition by requirejs.


    <meta charset="utf-8">
    <link rel="stylesheet" href="lib/node_modules/mocha/mocha.css" />
    <div id="mocha"></div>
    <script src="lib/node_modules/sinon/pkg/sinon.js"></script>
    <script src="lib/node_modules/mocha/mocha.js"></script>
    <script src="../scripts/require.js" data-main="test.config.js" ></script>


    baseUrl: "../scripts/src",
    paths: {
        chai: '../../test/lib/node_modules/chai/chai'

], function() {
    if (typeof mochaPhantomJS !== "undefined") {; }
    else {; }


chai can be added in the asynchronous module definition, but for some reason, sinon can't. Requirejs won't define it. Thats why its added in a script tag in the testRunner.html

define(['chai', 'UserMedia','NavigatorWrapper'], function(chai, UserMedia, NavigatorWrapper) {
    suite('NavigatorWrapper.hasGetUserMedia', function() {
        var sut, mockNavigator, instanceNavigator;
        setup(function() {
            instanceNavigator = new NavigatorWrapper();
            mockNavigator = sinon.mock(instanceNavigator);
            sut = new UserMedia(instanceNavigator);



You can see more in

3 Responses
Add your response

I think that TDD test-runner should be done in more transparent way.
While learning sinon I found that its author wrote the book
I am agree with Christian Johansen about test-runner concept - it should be fully automated and scalable, it should totally exclude F5 from usual workflow and should provide quick access to all sensible information in same place.
While Christian writing about jsTestDriver which requires Java, today available great test-runer "karma"

I have wrote boilerplate which integrates karma, mocha, chai, sinon for testing and RequireJS for making architecture. You may checkout it here:

over 1 year ago ·

What is that "karma-sound" folder? It really speaks-out when a test pass?? LOL

I have to try that

over 1 year ago ·

karma-sound folder is left for demonstrate how to make custom sound configuration in karma.conf.js instead of default sounds from karma-mp3-reporter @see karma.conf.js

over 1 year ago ·