Translate

Monday 17 April 2017

SinonJS - the spy

The example is more of a revealer to an error that can be quite vexing in sinon, node js parlance.

It is called "attempted to wrap undefined property as function" as if it were an attempt to murder.

The case in question is that of a call made to sinon's spy method

var theSpy = sinon.spy('get');
If used as such, this line will throw the error. The trick is to use the container that contains the 'get' method as the first parameter:


Not much of a sinon, but a spy nevertheless, much like Johnny English!


The spy method of sinon helps you to understand how many times a method call happened and it can also help you understand that if at all a call did get made to a method. This can be helpful in calls over the wire, say, http.

You need mocha, sinonjs and nodejs to run the example.

Below is the code.

test.js
var assert = require('assert');
var sinon = require('sinon');

var http = require('http');
var api = require('../myapi.js');
describe('testingBlogPost', function() {
var theSpy = sinon.spy(api,'get'); //  the first parameter will resolve the undefined property method

it('should get result to compare', function() {
var expected = 'Moved Permanently';
api.get(function(err, result) {
....
});
api.get(function(err, result) {
...
});
console.log(theSpy.callCount);
});
});


myapi.js

var http = require('http');
function myApi(){};

myApi.prototype = {
get: function(req,res) {
var req = http.request({
hostname: 'ravichandranjv.blogspot.in',
path: '/2017/04/how-to-setup-middle-game.html'
}, function(response) {
var data = '';
response.on('data', function(chunk) {
data += chunk;
});
response.on('end', function() {
res.send(data);
});
});
req.end();
}
}
module.exports = new myApi();


And the result, because the get method was twice called


Of course, another reason for writing the test also helps in knowing what if bots were to call posts on my blog! :)


Happy spying!

No comments: