Stubbing a promisified function with sinon and bluebird - javascript

In the file I would like to test, I have the following code:
var httpGet = Promise.promisify(require("request").get);
httpGet(endpoint, {
auth: {bearer: req.body.access_token},
json: true
})
.then(...)
Now, in my tests, I want to make sure that httpGet was called once, and make sure the parameters are valid. Before being promisified, my test looked like this:
beforeEach(function () {
request.get = sinon.stub()
.yields(null, null, {error: "test error", error_description: "fake google error."});
});
afterEach(function () {
expect(request.get).to.have.been.calledOnce();
var requestArgs = request.get.args[0];
var uri = requestArgs[0];
expect(uri).to.equal(endpoint);
//...
});
Unfortunately this no longer works when request.get is promisified. I tried stubbing request.getAsync instead (since bluebird appends "Async" to promisified functions), but that does not work either. Any ideas?

Promise.promisify doesn't modify the object, it simply takes a function and returns a new function, it is completely unaware that the function even belongs to "request".
"Async" suffixed methods are added to the object when using promisify All
Promise.promisifyAll(require("request"));
request.getAsync = sinon.stub()
.yields(null, null, {error: "test error", error_description: "fake google error."});
expect(request.getAsync).to.have.been.calledOnce();

Just for future reference I've solved this a bit differently, and I think a little cleaner. This is typescript, but basically the same thing.
fileBeingTested.ts
import * as Bluebird from 'bluebird';
import * as needsPromise from 'needs-promise';
const methodAsync = Bluebird.promisify(needsPromise.method);
export function whatever() {
methodAsync().then(...).catch(...);
}
test.spec.ts
import * as needsPromise from 'needs-promise';
import * as sinon form 'sinon';
const methodStub = sinon.stub(needsPromise, method);
import { whatever } from './fileBeingTested';
Then you use the methodStub to manage what calls happen. You can ignore that it's being promisified and just manage it's normal behavior. for example if you need it to error.
methodStub.callsFake((arg, callback) => {
callback({ error: 'Error' }, []);
});
The promisified version will throw the error and you'll get it in the catch.

Anyone coming across this. I have small utility func
function stubCBForPromisify(stub) {
let cbFn = function() {
let args = [...arguments];
args.shift();
return stub(...args);
};
return cbFn.bind(cbFn, () => ({}));
}
In test
var getStub = sinon.stub().yields(null, {error: "test error", error_description: "fake google error."})
sinon.stub(require("request"), 'get', stubCBForPromisify(getStub))
expect(getStub).to.have.been.calledOnce();

I was running into trouble testing this using tape and proxyquire. I'm not sure what pattern/framework people are using that allowed them to modify the required'd request object directly as shown in the accepted answer. In my case, in the file I want to test I require('jsonFile'), then call bluebird.promisifyAll(jsonFile). Under normal conditions this creates a readFileAsync method that I want to stub. However, if during testing I try to use proxyquire to pass in a stub, the call to promisifyAll overwrites my stub.
I was able to fix this by also stubbing promisifyAll to be a no-op. As shown this might be too coarse if you rely on some of the async methods to be created as-is.
core.js:
var jsonFile = require('jsonfile');
var Promise = require('bluebird');
Promise.promisifyAll(jsonFile);
exports.getFile = function(path) {
// I want to stub this method during tests. It is
// created by promisifyAll
return jsonFile.readFileAsync(path);
}
core-test.js:
var proxyquire = require('proxyquire');
var tape = require('tape');
var sinon = require('sinon');
require('sinon-as-promised');
tape('stub readFileAsync', function(t) {
var core = proxyquire('./core', {
'jsonfile': {
readFileAsync: sinon.stub().resolves({})
},
'bluebird': { promisifyAll: function() {} }
});
// Now core.getFile() will use my stubbed function, and it
// won't be overwritten by promisifyAll.
});

Related

How to stub constructor

I am writing uni-test and tring to isolate my code as much as possible. I am using Mocha and chai for writing test and ES5 Syntax.
The problem is, I am not able to find any solution to stub constructor.
Q.reject(new Error(obj.someFunction());
In above example, I know how to test promise, how to stub my inner function, but how I can stub Error constructor? And how I can check callWithExactly(), etc.
oStubSomeFunction = sinon.stub(obj, "someFunction")
I am using for normal function. I didn't find any relevant example in ChaiDocumentation
If you really want to stub the Error constructor you can use the Node.js global namespace:
code.js
exports.func = function() {
return new Error('error message');
}
code.test.js
const { func } = require('./code');
const sinon = require('sinon');
const assert = require('assert');
describe('func', function () {
it('should create an Error', function () {
const errorStub = sinon.stub(global, 'Error'); // <= stub the global Error
errorStub.callsFake(function(message) { // <= use callsFake to create a mock constructor
this.myMessage = 'stubbed: ' + message;
});
const result = func();
errorStub.restore(); // <= restore Error before doing anything else
assert(result.myMessage === 'stubbed: error message'); // Success!
sinon.assert.calledWithExactly(errorStub, 'error message'); // Success!
});
});
If you do this you'll want to restore Error before doing absolutely anything else...even assertions work using Error so the original Error needs to be in place in case an assertion fails.
It's a lot safer to just spy on Error:
const { func } = require('./code');
const sinon = require('sinon');
describe('func', function () {
it('should create an Error', function () {
const errorSpy = sinon.spy(global, 'Error'); // <= spy on the global Error
func();
sinon.assert.calledWithExactly(errorSpy, 'error message'); // Success!
errorSpy.restore();
});
});
...and ultimately there is a limit to how isolated code under test can get. For something as low-level as Error you might want to look at leaving it completely intact and testing for a thrown Error using something like Chai's .throw assertion.

Javascript sinon testing callback

I'm trying to test that certain function is called in a callback, however I don't understand how to wrap the outer function. I'm using mocha as my testing suite, with chai as my assertion library, and sinon for my fakes.
fileToTest.js
const externalController = require('./externalController');
const processData = function processData( (req, res) {
externalController.getAllTablesFromDb( (errors, results) => {
// call f1 if there are errors while retrieving from db
if (errors) {
res.f1();
} else {
res.f2(results);
}
)};
};
module.exports.processData = processData;
In the end I need to verify that res.f1 will be called if there are errors from getAllTablesFromDb, and res.f2 will be called if there are no errors.
As can be seen from this snippet externalController.getAllTablesFromDb is a function that takes a callback, which in this case I have created using an arrow function.
Can someone explain how I can force the callback down error or success for getAllTablesFromDb so that I can use a spy or a mock to verify f1 or f2 was called?
var errorSpy = sinon.spy(res, "f1");
var successSpy = sinon.spy(res, "f2");
// your function call
// error
expect(errorSpy.calledOnce);
expect(successSpy.notCalled);
// without errors
expect(errorSpy.notCalled);
expect(successSpy.calledOnce);
One possible solution is to extract the callback then force that down the desired path of failure or success. This extraction can be done using a npm package called proxyquire. The callback is extracted by removing the require line from the beginning of the file then:
const proxyquire = require('proxyquire');
const externalController = proxyquire('path to externalController',
'path to externalController dependency', {
functionToReplace: (callback) => { return callback }
}
});
const extractedCallback = externalController.getAllTablesFromDb(error, results);
Then you can call extractedCallback with the parameters you want.
extractedCallback(myArg1, myArg2);
and set a spy on res.f1 and res.f2
sinon.spy(res, 'f1');
And do any assertion logic you need to.

Why the code in Promise.then() not been called?

Why the code in Promise.then() not been called?
I'm writting a server with expressjs and bluebird promise.When I tried to promisify a function using Promise.promisify(), I found that the code I wrote in Promise.then() doesn't work.My codes are as follow
var Promise = require('bluebird');
var test = function(req) {
console.log('123');
};
var regist=Promise.promisify(test);
app.post('/test', function (req, res) {
reg.regist()
.then(function () {
console.log('456');
});
I post a request to '/test' and only saw 123 printed in the console.How could I make the codes in the Promise.then() work?
Promise.promisify creates a mechanism that automatically passes in a callback function as the last argument to your original function. Your function doesn't take a callback function and never calls one, so there's no way for the promise to resolve.
If your function is not asynchronous, there isn't much point in promisifying it, but here's how you could do so:
var test = function(req, callback) {
console.log('123');
callback();
};
var regist = Promise.promisify(test);
var request = { someProperty: 'some value'};
regist(request)
.then(function() {
console.log('456');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.4.7/bluebird.min.js"></script>

How to unit test a function which calls another that returns a promise?

I have a node.js app using express 4 and this is my controller:
var service = require('./category.service');
module.exports = {
findAll: (request, response) => {
service.findAll().then((categories) => {
response.status(200).send(categories);
}, (error) => {
response.status(error.statusCode || 500).json(error);
});
}
};
It calls my service which returns a promise. Everything works but I am having trouble when trying to unit test it.
Basically, I would like to make sure that based on what my service returns, I flush the response with the right status code and body.
So with mocha and sinon it looks something like:
it('Should call service to find all the categories', (done) => {
// Arrange
var expectedCategories = ['foo', 'bar'];
var findAllStub = sandbox.stub(service, 'findAll');
findAllStub.resolves(expectedCategories);
var response = {
status: () => { return response; },
send: () => {}
};
sandbox.spy(response, 'status');
sandbox.spy(response, 'send');
// Act
controller.findAll({}, response);
// Assert
expect(findAllStub.called).to.be.ok;
expect(findAllStub.callCount).to.equal(1);
expect(response.status).to.be.calledWith(200); // not working
expect(response.send).to.be.called; // not working
done();
});
I have tested my similar scenarios when the function I am testing returns itself a promise since I can hook my assertions in the then.
I also have tried to wrap controller.findAll with a Promise and resolve it from the response.send but it didn't work neither.
You should move your assert section into the res.send method to make sure all async tasks are done before the assertions:
var response = {
status: () => { return response; },
send: () => {
try {
// Assert
expect(findAllStub.called).to.be.ok;
expect(findAllStub.callCount).to.equal(1);
expect(response.status).to.be.calledWith(200); // not working
// expect(response.send).to.be.called; // not needed anymore
done();
} catch (err) {
done(err);
}
},
};
The idea here is to have the promise which service.findAll() returns accessible inside the test's code without calling the service. As far as I can see sinon-as-promised which you probably use does not allow to do so. So I just used a native Promise (hope your node version is not too old for it).
const aPromise = Promise.resolve(expectedCategories);
var findAllStub = sandbox.stub(service, 'findAll');
findAllStub.returns(aPromise);
// response = { .... }
controller.findAll({}, response);
aPromise.then(() => {
expect(response.status).to.be.calledWith(200);
expect(response.send).to.be.called;
});
When code is difficult to test it can indicate that there could be different design possibilities to explore, which promote easy testing. What jumps out is that service is enclosed in your module, and the dependency is not exposed at all. I feel like the goal shouldn't be to find a way to test your code AS IS but to find an optimal design.
IMO The goal is to find a way to expose service so that your test can provide a stubbed implementation, so that the logic of findAll can be tested in isolation, synchronously.
One way to do this is to use a library like mockery or rewire. Both are fairly easy to use, (in my experience mockery starts to degrade and become very difficult to maintain as your test suite and number of modules grow) They would allow you to patch the var service = require('./category.service'); by providing your own service object with its own findAll defined.
Another way is to rearchitect your code to expose the service to the caller, in some way. This would allow your caller (the unit test) to provide its own service stub.
One easy way to do this would be to export a function contstructor instead of an object.
module.exports = (userService) => {
// default to the required service
this.service = userService || service;
this.findAll = (request, response) => {
this.service.findAll().then((categories) => {
response.status(200).send(categories);
}, (error) => {
response.status(error.statusCode || 500).json(error);
});
}
};
var ServiceConstructor = require('yourmodule');
var service = new ServiceConstructor();
Now the test can create a stub for service and provide it to the ServiceConstructor to exercise the findAll method. Removing the need for an asynchronous test altogether.

Building tests with mocha for async code (request)

I am trying to create unit tests with Mocha and Chai on Node.JS. Here is a simplified version of the function to test:
router.cheerioParse = function(url, debugMode, db, theme, outCollection, _callback2) {
var nberror = 0;
var localCount = 0;
console.log("\nstarting parsing now : " + theme);
request(url, function(error, response, body) {
//a lot of postprocessing here that returns
//true when everything goes well)
});
}
Here is the test I am trying to write:
describe('test', function(){
it('should find documents', function(){
assert( true ==webscraping.cheerioParse("http://mytest.com, null, null, null ,null,null ));
});
})
How can the request function return true to have it passed to the test? I have tried to use promises but it didn't work either. In this case should I put the return statement in the then callback? What is the best approach?
You should mock request function. You could use e.g. sinon stubs for this (they provide returns function for defining returning value).
In general - the idea of unit tests is to separate particular function (unit of test) and stub every other dependency, as you should do with request :)
To do so, you have to overwrite original request object, e.g. :
before(function() {
var stub = sinon.stub(someObjectThatHasRequestMethod, 'request').returns(true);
});
And after running tests you should unstub this object for future tests like that:
after(function() {
stub.restore();
});
And that's all :) You could use both afterEach/after or beforeEach/before - choose the one that suits you better.
One more note - because your code is asynchronous, it is possible that your solution might need more sophisticated way of testing. You could provide whole request mock function and call done() callback when returning value like this:
it('should find documents', function(done) {
var requestStub = sinon.stub(someObjectThatHasRequestMethod, 'request',
function(url, function (error, response, body) {
done();
return true;
}
assert(true === webscraping.cheerioParse("http://mytest.com, null, null, null ,null,null ));
requestStub.restore();
});
You could find more info here:
Mocha - asynchronous code testing

Categories