During the past weeks I was involved in developing BoilerplateJS, a JavaScript reference architecture for large scale web applications. BoilerplateJS was developed based on RequireJS modules. I was involved in setting up unit testing for BoilerplateJS. One of our main requirements was to mock RequireJS module dependencies. After a lot of searching I came across testr.js. Testr.js can be used with almost any unit testing framework.

Assume that we have the following setup:

+-index.html
+-main.js
+-module1.js
+-dependencies/
+-----dependency1.js
+-libs/
+-----require.js
+-----testr.js

Index file contains the links to the scripts. Note that you have to import testr.js after importing RequireJS.


<script type="text/javascript" src="./libs/require.js" data-main="tests"></script><script type="text/javascript" src="./libs/testr.js"></script>

My dependency1.js file contains:

define([], function(){
	var dep = function(){
		this.getText = function(){
			return 'Original Dependancy';
		};
	};
	return dep;
});

It contains a getText() method which returns a string.
Lets assume that module1.js has used the above dependency as follows:

define(['dependencies/dependancy1'], function(Dependancy1){
	var module = function(){
		this.run = function(){
			var d1 = new Dependancy1();
			console.log(d1.getText());
		};
	};
	return module;
});

You can see that when the run method of Module1 is called, it calls the getText() method of the dependency. Therefore if you execute the run method of Module1, you should see ‘Original Dependancy’ on the console.
Our aim in this scenario is to replace dependancy1 with a mock object during run time.
Our tests.js file contains:

require(['module1'], function(){

	var fakeDep = function(){
		this.getText = function(){
			return 'Fake Dependancy';
		};
	};

	var Module1 = testr('module1', {
		'dependancies/dependancy1':fakeDep
	});

	var m1 = new Module1();
	m1.run();
});

Here, we create a fakeDep object that has the same methods as the original dependency, and then passes it to testr function with the related file path. Now, instead of loading the original dependency, testr.js loads the module with the provided fake dependency. When you run the above index.html, you will see the fake dependency being executed and ‘Fake Dependancy’ being printed on the console.