SinonJS FakeServer with Browserify or Node

If you’ve tried using NPM’s SinonJS Fake Server with Browserify or Node you will experience this bug ( https://github.com/cjohansen/Sinon.JS/issues/319 ): FakeServer is not wrapped for proper ‘require’ usage.

If this ticket’s status has changed to resolved, that is probably the best solution and you can stop reading.

Otherwise I found that the minified version from a CDN includes fakeServer for you: http://cdnjs.cloudflare.com/ajax/libs/sinon.js/1.7.3/sinon-min.js

I download this file and use it with a browserify-shim, then it all works as it should.


var fs = require('fs');

var cluster = fs.readFileSync(__dirname + ‘/cluster.json’, ‘utf8’);
var projectSites = fs.readFileSync(__dirname + ‘/project-sites.json’, ‘utf8’);
var filters = fs.readFileSync(__dirname + ‘/filters.json’, ‘utf8’);
var indicators = fs.readFileSync(__dirname + ‘/indicators.json’, ‘utf8’);

var fakeServer = {
server: null,

init: function(){
this.server = sinon.fakeServer.create();
this.server.autoRespond = true;

// Create paths for mock API
this._addPath(cluster, ‘/rest/gis/cluster’);
this._addPath(filters, ‘/rest/gis/filters’);
this._addPath(projectSites, ‘/rest/gis/project-sites’);
this._addPath(indicators, ‘/rest/gis/indicator-layers’);

},

_addPath: function(resp, path){
this.server.respondWith(‘GET’,
path,
[200, { ‘Content-Type’: ‘application/json’ }, resp]);
}
};

fakeServer.init();

 

Post Tagged with , ,