Stub service layer with RequireJS

require While working on Single Page Apps (previously Rich Internet App), people usually end up concentrating on the server or the client side. In this situation it is handy for the UI developers to be able to work with fake/mock/stub Service layer. There are frameworks for mocking the service layer, like Mockjax, but since I was using RequireJS I went with a simpler RequireJS based solution. Basically I wanted to replicate profiles as available in the Spring framework. I got to this with a neat little trick I saw on the Forums.

In the main application, I inject a Service like so:

if (inTestMode()) {
 require.paths['app/clients/RealClient'] = 'test/clients/StubClient';
function inTestMode() {
 var params =;
 return params && params.indexOf('mode=test') >= 0;

Note that the main Require config has previouly been done. Here I tweak it a bit for injecting the stub. The test mode is triggered from an app URL parameter. So, instead of calling


you would call


At, this point RequireJS will substitute the stub client for the real one. The app code remains completely unaffected.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s