09 Jun 2014

Using Express Router instead of express-namespace

express 4.0 has been out for a while and it seems people are still using express-namespace. According to npm it had 183 downloads on the 8th of June.

express-namespace hasnt been updated in nearly two years and it can now be replaced with the Router that comes with express 4.

Also I’ve found that the middleware mounting on namespace roots would mount it at the the application level. This is else that the router solves as it allows you to seperate out routes into different modules with its own middleware.

Here is the example from express-namespace written using the Router in express 4.0.

var express = require('express'),
    forumRouter = express.Router(),
    threadRouter = express.Router(),
    app = express();

forumRouter.get('/:id/((view)?)', function(req, res){
  res.send('GET forum ' + req.params.id);
});

forumRouter.get('/:id/edit', function(req, res){
  res.send('GET forum ' + req.params.id + ' edit page');
});


forumRouter.delete('/:id', function(req, res){
  res.send('DELETE forum ' + req.params.id);
});

app.use('/forum', forumRouter);

threadRouter.get('/:id/thread/:tid', function(req, res){
  res.send('GET forum ' + req.params.id + ' thread ' + req.params.tid);
});

forumRouter.use('/', threadRouter);

app.listen(3333);

A little bit more typing but easier to explain to others and no monkey patching weirdness of express-namespace.

The routes are more little more explicitly defined.

Hope this helps.

28 Apr 2014

Mocking a function that returns a (bluebird) Promise

With Sinon.JS mocking functions are quite easy. Here is how to stub a function that returns a Promise.

Demonstrated with a potato quality example. Imagine the following code is in a file named db.js

var Promise = require('bluebird');

module.exports.query = function query(q) {
  return Promise.resolve([
    {
      username: 'bulkan',
      verified: true
    }
  ])
}

Using bluebird we simulate a database query which returns a Promise that is resolved with an Array of Objects.

Imagine the following code located in users.js;

var db = require('./db');

module.exports.getVerified = function getVerified(){
  return db.query('select * from where verified=true');
}

The mocha unit test for the above which stubs out db.query that is called in users.js;

var db = require('./db')
  , should  = require('chai').should()
  , sinon = require('sinon')
  , users;

describe('Users', function(){
  var sandbox, queryStub;

  beforeEach(function(){
    sandbox = sinon.sandbox.create();
    queryStub = sandbox.stub(db, 'query');
    users = require('./users');
  });

  afterEach(function(){
    sandbox.restore();
  });

  it('getVerified should return a resolved Promise', function(){
    queryStub.returns(Promise.reject('still resolved'));
    var p = users.getVerified();
    p.isResolved().should.be.true;
    return p;
  });
})

In the beforeEach and afterEach functions of the test we create a sinon sandbox which is slightly over kill for this example but it allows you to stub out a few methods without worrying about manually restoring each stub later on as you can just restore the whole sandbox as demonstrated in the afterEach.

There is one test case that tells the queryStub to return a Promise that is rejected. Then test that the promise that users.getVerified returns is resolved. Mocha now will wait until Promises that are returned from its to resolve.

Sorry about the potato quality example, been trying to think of a better example. Any suggestions ?

Hope this helps.

24 Apr 2014

Using mockery to mock modules for Node.js testing

In a previous article I wrote about mocking methods on the request module.

request also supports another workflow in which you directly call the imported module;

var request = require('request');

request({
  method: 'GET',
  url: 'https://api.github.com/users/bulkan'
}, function(err, response, body){
  if (err) {
    return console.err(err);
  }

  console.log(body);
})

You pass in an options object specifying properties like the HTTP method to use and others such as url, body & json.

Here is the example from the previous article updated to use request(options);

var request = require('request');

function getProfile(username, cb){
  request({
    method: 'GET',
    url: 'https://api.github.com/users/' + username
  }, function(err, response, body){
    if (err) {
      return cb(err);
    }
    cb(null, body);
  });
}

module.exports = getProfile;

Its not that big of a change. To unit test the getProfile function we will need to mock out request module that is being imported by the module that getProfile is defined in. This where mockery comes in. It allows us to change what gets returned when a module is imported.

Here is a mocha test case using mockery. This assumes that the above code is in a file named gh.js.

var sinon = require('sinon')
  , mockery = require('mockery')
  , should = require('chai').should();

describe('User Profile', function(){
  var requestStub, getProfile

  before(function(){
    mockery.enable({
      warnOnReplace: false,
      warnOnUnregistered: false,
      useCleanCache: true
    });

    requestStub = sinon.stub();

    // replace the module `request` with a stub object
    mockery.registerMock('request', requestStub);

    getProfile = require('./gh');
  });

  after(function(){
    mockery.disable();
  });

  it('can get user profile', function(done){
    requestStub.yields(null, {statusCode: 200}, {login: "bulkan"});

    getProfile('bulkan', function(err, result){
      if(err) {
        return done(err);
      }
      requestStub.called.should.be.equal(true);
      result.should.not.be.empty;
      result.should.have.property('login');
      done();
    });
  });
})

mockery hijacks the require function and replaces modules with our mocks. In the above code we register a sinon stub to be returned when require('request') is called. Then we configure the mock in the test using the method .yield on the stub to a call the callback function passed to request with null for the error, an object for the response and another object for the body.

You can write more tests

Hope this helps.

09 May 2013

HTML5 Manifest File & Nginx

Ive been developing a HTML5 game using the LimeJS framework. As I am targetting iPhone and iPod Touches I asked my lovely girlfriend fiance to design me an app icon and hopefully In the near future she will also have give startup images too.

As I dont want to load the icon and startup images via the network every time the app loads, I thought I would cache it “offline”. To do this you need to create a manifest file which your web server needs to set a specific content-type header which is just text/cache.manifest.

To load a manifest file you need to add an attribute called manifest that points to your manifest file. It can be a relative path.

<!DOCTYPE HTML>
<html manifest="mysite.manifest">
...

Here is how the rest of my HTML file looks like

...
<head>
    <title>site</title>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <link rel="apple-touch-icon" href="/assets/icon.png"/>
    <script type="text/javascript" src="site.js"/>
</head>
    <body></body>
</html>

The manifest file tells the browser which files to store locally, the syntax for it kind of reminds me of INI files, but not quite. My manifest file looks like following;

CACHE MANIFEST
/assets/icon.png

NETWORK:
site.js

This tells the site to cache/store the png image for the app icon. The file listing following the NETWORK: section tells the browser to always load the files from the network. More info is available in this link

If you are using Nginx like I am, then you need to change the file mime.types and add the following

text/cache.manifest       manifest;

Which just tells Nginx to serve up file resources ending with manifest with the content-type header of test/cache.manifest.

Hope this helps.

29 Apr 2013

Using Custom Events With LimeJS

LimeJS is an open source JavaScript HTML5 game creation framework built using Google Closure. In this article I will show you how to create a new event type and dispatch it, which is more so a Closure feature than LimeJS. I am going to assume you have installed LimeJS if not read the instruction.

We will create a simple game that will display a Sprite with the same width and height as the viewport. We will listen to touch & click events on this Sprite, generate a random number when these events fired, between 0-256 and fire a custom event once this number is greater than 128.

This number will be than used to change the color of our Sprite.

The game we will create is kind of a contrived example with zero playability but I hope it will serve the purpose introducing custom events to you.

Let there be events

Create a new LimeJS project by typing the following, which will create a directory called events_tutorial which will contain two files, events_tutorial.html and events_tutorial.js

bin/lime.py create events_tutorial

I like to create a separate file to store all my event types and the dispatcher so lets start with that file.

Create a new file in the events_tutorial directory and call it events.js and copy/paste in the following.

Closure provides goog.events.EventTarget for dispatching events and listening to them. The documentation blurb writes;

Inherit from this class to give your object the ability to dispatch events. Note that this class provides event sending behaviour, not event receiving behaviour: your object will be able to broadcast events, and other objects will be able to listen for those events using goog.events.listen().

As goog.events.EventTarget provides the ability to dispatch events we just create a new instance instead of inheriting from it which is done on line 6.

To distinguish between events we will need to create a subclass from goog.events.Event which is done on lines 8-10. The important part of that code block is the call to the base class on line 9. Make sure you use pass a unique string as this will be the string that will be used to identify the event.

Time to use this event in a new Sprite.

Create a new new file in events_tutorial called coloredsprite.js directory and paste in the following.

Here we create a subclass from lime.Sprite_ in which the constructor requires the width and height parameters that define it’s size. The changeColor method will be the callback method which will be registered in the event listener when the user touches or clicks on the Sprite. This method is straight forward, generate a random number and if it is greater than 128 fire a new instance of our event class we defined in events.js.

Before we move on run the following so that we update our dependencies.

bin/lime.py update

Let us now connect all of this together in events_tutorial.js which will look like the following.

Most of the code above is boiler plate code. We create an instance of Director, Scene and Layer. The getting started guide for LimeJS_ describes what each of these objects do.

What is important is that we also create an instance of our ColoredSprite class on line 19 and add it to the Layer called target. We than listen to the custom event that is being dispatched on line 24 using the unique string we passed into the call to the base class on line 9 of events.js.

When the event fires we create a Label, add it to target and animate it.

Hope this blog post helped. If you have questions comment on the individual Gist’s or send me a tweet @bulkanevcimen