I've got an express based app running on node.js 0.12.2 which uses the s3.headBucket method from aws-sdk 2.1.22 to return a JSON response depending upon whether a particular bucket exists or not.
I've been struggling to directly stub out the call to s3.headBucket with sinon. I've managed to work around this by creating an s3wrapper module which just requires the aws-sdk and instantiates and returns the s3 variable, however, I'm sure this can be done without using the wrapper module and can instead be stubbed directly with sinon, can anyone point me in the right direction?
Below is the currently working code (with the wrapper module s3wrapper.js which I'd like to remove and handle the stubbing in my status_router_spec.js file). In other words, I'd like to be able to call s3.headBucket({Bucket: 'whatever' ... instead of s3wrapper.headBucket({Bucket: ' ... and be able to stub out this s3.headBucket call with my own response.
status_router_spec.js
var chai = require('chai'),
sinon = require('sinon'),
request = require('request'),
myHelper = require('../request_helper')
var expect = chai.expect
var s3wrapper = require('../../helpers/s3wrapper')
describe('My router', function () {
describe('checking the service status', function () {
var headBucketStub
beforeEach(function () {
headBucketStub = sinon.stub(s3wrapper, 'headBucket')
})
afterEach(function () {
s3wrapper.headBucket.restore()
})
describe('when no errors are returned', function () {
it('returns healthy response', function (done) {
// pass null to represent no errors
headBucketStub.yields(null)
request.get(myHelper.appUrl('/status'), function (err, resp, body) {
if (err) { done(err) }
expect(JSON.parse(body)).to.deep.eql({
healthy: true,
message: 'success'
})
done()
})
})
})
})
})
s3wrapper.js
var AWS = require('aws-sdk')
var s3 = new AWS.S3()
module.exports = s3
status_router.js
var Router = require('express').Router
var s3wrapper = require('../helpers/s3wrapper.js')
var router = new Router()
function statusHandler (req, res) {
s3wrapper.headBucket({Bucket: 'some-bucket-id'}, function (err) {
if (err) {
return res.json({ healthy: false, message: err })
} else {
return res.json({ healthy: true, message: 'success' })
}
})
}
router.get(/^\/status\/?$/, statusHandler)
module.exports = router
Answering this question for the benefit of #ippomakunochi who requested a follow up response.
We ended up using rewire to directly set a stub on the s3 library. For example, we stubbed the getObject call for the s3 library using the following:
s3stub = { getObject: sinon.stub(), listObjects: sinon.stub() }
revert = s3.__set__('s3', s3stub)
Here's the complete code:
../../../build/app/helpers/s3
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
module.exports = {
get: function get(options, callback) {
var requestOptions = { Bucket: module.exports.bucket(), Key: options.productId + '.json' };
s3.getObject(requestOptions, function (err, data) {
if (err) { // handle err }
try {
var productData = JSON.parse(data.Body);
} catch (e) {
// handle error
}
return callback(null, productData);
});
}
}
}
test/unit/app/helpers/s3_spec.js
var AWS = require('aws-sdk')
var chai = require('chai')
var sinon = require('sinon')
var sinonChai = require('sinon-chai')
var chaiSubset = require('chai-subset')
var rewire = require('rewire')
var s3 = rewire('../../../build/app/helpers/s3')
chai.use(chaiSubset)
chai.use(sinonChai)
var expect = chai.expect
describe('S3', function () {
var s3stub, revert
beforeEach(function () {
s3stub = { getObject: sinon.stub(), listObjects: sinon.stub() }
revert = s3.__set__('s3', s3stub)
})
afterEach(function () {
revert()
})
describe('#get', function () {
context('when no errors are returned by s3', function () {
it('returns a product', function (done) {
var productResponse = helper.fixture.body('product.json')
s3stub.getObject.yields(null, productResponse)
s3.get({ productId: '1234' }, function (err, res) {
expect(err).to.not.exist
expect(res).to.containSubset({name: 'long sleeve shirt', 'retailer_code': 'retailer-1'})
done()
})
})
})
context('when s3 returns a NoSuchKey error', function () {
it('returns a NotFoundError', function (done) {
var s3Error = AWS.util.error(new Error(), { name: 'NoSuchKey' })
s3stub.getObject.yields(s3Error)
s3.get({ productId: '1234' }, function (err) {
expect(err.message).to.eql('1234 is not found in s3')
expect(err.output.statusCode).to.eql(404)
done()
})
})
})
})
Related
I want to make 100% coverage on this function with node-tap but I can't mock the error part, it always throw
Cannot find module 'create' Require stack: - /home/mptr8/Code/Projects/me/fastify-example/fastify-postgres/test/integration.js
But I have create function on my query.js file, what do I do wrong here? Why it doesn't invoke the method?
t.mock("../query.js", {
create: () => {
throw new Error();
},
});
I also try this combination, because query.js are dependent on db.js. Now the mock error gone but still I'm not getting the error throw from my fastify.inject.
t.mock("../db.js", {
"../query.js": {
create: () => { throw new Error() },
},
});
app.post("/", async (request, reply) => {
try {
const { body } = request;
const book = create(body.title);
reply.send(book);
} catch (error) {
// this part are not covered
reply.code(500).send({ message: "internal server error" });
}
});
here are my complete code. You can see the full code on this github repository.
// server.js
const fastify = require("fastify");
const {
migration,
create,
} = require("./query");
const db = require("./db");
function build(opts = {}) {
const app = fastify(opts);
migration();
app.post("/", async (request, reply) => {
try {
const { body } = request;
const book = create(body.title);
reply.send(book);
} catch (error) {
reply.code(500).send({ message: "internal server error" });
}
});
app.addHook("onClose", (_instance, done) => {
db.close();
done();
});
}
module.exports = build;
// db.js
const { Pool } = require("pg");
const pool = new Pool({
connectionString:
"postgresql://postgres:postgres#localhost:5432/fastify_postgres?schema=public",
});
module.exports = {
query: (text, params) => pool.query(text, params),
close: () => pool.end(),
};
// query.js
const db = require("./db");
async function migration() {
await db.query(`
CREATE TABLE IF NOT EXISTS books (
id serial PRIMARY KEY,
title varchar (255) NOT NULL
)
`);
}
async function create(title) {
return await db.query("INSERT INTO books (title) VALUES ($1)", [title]);
}
module.exports = { migration, create };
// test.js
const tap = require("tap");
const fastify = require("../server");
tap.test("coba", async (t) => {
const app = await fastify();
t.test("should success create books", async (t) => {
const response = await app.inject({
method: "POST",
url: "/",
payload: {
title: "Hello,World!",
},
});
t.equal(response.statusCode, 200);
});
t.test("should throw error", async (t) => {
const app = await fastify();
// it doesn't throw the error :((
t.mock("../query.js", {
create: () => {
throw new Error();
},
});
const response = await app.inject({
method: "POST",
url: "/",
payload: {
title: "Hello,World!",
},
});
t.equal(response.statusCode, 500);
// call app close on last test child to close app and db properly
app.close();
});
});
You should use the returned value by the t.mock function:
const build = t.mock({
"../server": {
"./query.js": {
create: () => { throw new Error() },
}
}
})
const app = await build({})
I'm using nodejs exif library to retrieve metadata from JPEG files.
this lib is used this way :
import * as exif from 'exif'
new exif.ExifImage('path_to_file.jpg', function(err, metadata){ ... })
I've found everywhere how to stub a class method using sinon, pretty simple.
But I don't get how to stub this class constructor so that metadata (or err if I want to test failing case) will be the stubbed value I need to perform my test.
We can still use Sinon with callsFake function. Here is the example:
// src.js
const exif = require("exif");
function readImage() {
// convert to promise for easier testing
return new Promise((resolve, reject) => {
new exif.ExifImage("path_to_file.jpg", function(err, metadata) {
if (err) {
reject(err);
}
resolve(metadata);
});
});
}
module.exports = { readImage };
meanwhile for test
// test.js
const sinon = require('sinon');
const src = require('./src');
const exif = require('exif');
const expect = require('chai').expect;
describe('test exifimage', () => {
let exifStub;
beforeEach(function() {
exifStub = sinon.stub(exif, 'ExifImage')
})
afterEach(function() {
sinon.restore();
})
it('test when success', async () => {
const metadata = 'cinta';
// mock ExifImage as similar as its function signature
exifStub.callsFake((filename, callback) => {
callback(null, metadata); // error is set as null then we set metadata
});
const response = await src.readImage();
expect(response).to.equal(metadata);
});
it('test when error', async () => {
const errorMessage = 'this is error';
exifStub.callsFake((filename, callback) => {
callback(errorMessage); // specify error, error is defined as first param
});
try {
await src.readImage();
} catch (error) {
expect(error).to.equal(errorMessage);
}
});
});
Hope it helps
I have a function for which I am writing unit test but that function is calling another function and there I am not able to mock/stub that function.
for example :
function getValue( param1, param2, callback){
getData(param1, param3).then( response) => {
return callback();
}, (err) => {
return callback();
});
}
So I don't know how to mock getData() function.
Here is a working example that demonstrates what you are trying to do:
lib.js
function getData(param1, param2) {
return fetch('someUrl'); // <= something that returns a Promise
}
exports.getData = getData;
code.js
const lib = require('./lib');
export function getValue(param1, param2, callback) {
return lib.getData(param1, param2).then(response => {
callback(response);
}).catch(err => {
callback(err);
});
}
exports.getValue = getValue;
code.test.js
const sinon = require('sinon');
const lib = require('./lib');
const { getValue } = require('./code');
describe('getValue', () => {
it('should do something', async () => {
const stub = sinon.stub(lib, 'getData');
stub.resolves('mocked response');
const callback = sinon.spy();
await getValue('val1', 'val2', callback);
sinon.assert.calledWithExactly(stub, 'val1', 'val2'); // Success!
sinon.assert.calledWithExactly(callback, 'mocked response'); // Success!
});
});
Update
OP added in the comments that they can't use async / await and are exporting the function using module.exports = getData;.
In that case the module export is the function and the entire module needs to be mocked with something like proxyquire.
The assertions should be done in a then callback and the test should return the resulting Promise so mocha knows to wait for it to resolve.
Updated example:
lib.js
function getData(param1, param2) {
return fetch('someUrl'); // <= something that returns a Promise
}
module.exports = getData;
code.js
const getData = require('./lib');
function getValue(param1, param2, callback) {
return getData(param1, param2).then(response => {
callback(response);
}).catch(err => {
callback(err);
});
}
module.exports = getValue;
code.test.js
const sinon = require('sinon');
const proxyquire = require('proxyquire');
describe('getValue', () => {
it('should do something', () => {
const stub = sinon.stub();
stub.resolves('mocked response');
const getValue = proxyquire('./code', { './lib': stub });
const callback = sinon.spy();
return getValue('val1', 'val2', callback).then(() => {
sinon.assert.calledWithExactly(stub, 'val1', 'val2'); // Success!
sinon.assert.calledWithExactly(callback, 'mocked response'); // Success!
});
});
});
function getValue( param1, param2, callback){
getData(param1, param3).then( response) => {
callback(response);
});
}
getvalue(param1, param2, function(error, response)) {
console.log(response)
}
It might help you.
I am new to nodejs.
How do I stub my return result which is a callback.
I know that I should not access the DB when doing testing.
I am doing unit testing at the controller level.
Here is my flow on how I going to do my test based on my understanding from java.
Mock Request and Response.
Set param of request.
Mock bookDAO.selectBook so that it return a user defined result. Thus not calling DB.
Verify / assert the value of the return results. (i.e. Response must be 200, JSON format, must have column BOOK_ID, BOOK_TITLE, etc)
However, i was not able to successfully mock my function. After running npm test, this is the error that I am receiving.
2018-10-02T10:00:17.809 1) Book service
1. should list a SINGLE Book /book/id GET:
Error: selectBook cannot yield to '[object Object]' since no callback was passed. Received [XCV1234, function (result) {
res.status(200).json({
message: format(message.DEFAULT_MSG, "GET", constant.MODULE_URL),
result: result
});
}]
at throwYieldError (node_modules\sinon\lib\sinon\call.js:22:11)
at Object.yieldToOn (node_modules\sinon\lib\sinon\call.js:167:13)
at Object.yieldTo (node_modules\sinon\lib\sinon\call.js:156:31)
at Function.spyApi.(anonymous function) [as yieldTo] (node_modules\sinon\lib\sinon\spy.js:416:61)
at Context.it (test\controller\BookController.spec.js:47:17)
Am i doing it the right way? how do i return the callback result ?
bookController.js:
exports.getBook = (req, res) => {
//get from request
const id = req.params.id;
const params = [id];
bookDao.selectBook(params, function (result) {
res.status(200).json({
message: format(message.DEFAULT_MSG, "GET", constant.MODULE_URL),
result: result
});
});
};
bookDao.js:
function selectBook(params, callback) {
pool.open(connString, function (err, conn) {
conn.queryResult(query.SQL_SELECT, params, function (err, result) {
if (err) {
console.error(err);
return conn.closeSync();
}
var data = result.fetchAllSync();
// only when successful then call closeSync
result.closeSync();
return callback(data);
});
conn.close();
});
}
bookRest.js:
module.exports = (app) => {
// map to controller
const controller = require('../controller/bookController');
app.route(constant.MODULE_URL + '/:id').get(controller.getbook);
app.route(constant.MODULE_URL).put(controller.updateBooks);
};
bookController.spec.js:
process.env.NODE_ENV = 'test';
const sinon = require('sinon');
const chai = require('chai');
const chaiHttp = require('chai-http');
const should = chai.should();
const httpMocks = require('node-mocks-http');
let server = require('../../../main.js');
const bookController = require('../../../controller/bookController.js');
const bookDao = require('../../../dao/bookDao.js');
chai.use(chaiHttp);
let req = httpMocks.createRequest();
let res = httpMocks.createResponse();
describe('Book service', () => {
beforeEach(() => {
});
afterEach(() => {
});
it('1. should list a SINGLE Book /book/id GET', (done) => {
req.params.id = "XCV1234";
const selectbook = sinon.stub(bookDao, "selectbook");
bookController.getbook(req, res);
selectbook.yieldTo({BOOK_ID : "XCV1234"});
res.should.have.status(200);
res.should.be.json;
res.body.should.be.a('object');
res.body.result[0].should.include.keys(
'BOOK_ID'
);
sinon.restore();
done();
});
});
I'm afraid yieldsTo is not the appropriate method to use for this case. Based on documentation, this method is intended to target callback that passed as property as in
sinon.stub(jQuery, "ajax").yieldsTo("success", [1, 2, 3]);
jQuery.ajax({
success: function (data) {
assertEquals([1, 2, 3], data);
}
});
To solve your problem, we can use yields so it will be like:
...
// should be stubbed before `getbook` is called
sinon.stub(bookDao, "selectbook").yields({
BOOK_ID: "XCV1234"
});
bookController.getbook(req, res);
res.should.have.status(200);
...
Hope it helps
I got a problem with Multer, undefined req.files.path field
First, my Express.js route is:
routes.js
router.post('/', function(req, res, next){
// id, name, usersArray[], info, iconImg, headerImg
var dataObject = new MyMongooseDataObject();
// Receive data
dataObject.id = uuid.v4();
dataObject.name = req.body.name;
dataObject.usersArray = req.body.usersArray;
dataObject.info = req.body.info;
return someBindingWrapperToStoreTheFile.postFile(uuid.v4(), [req.files.iconImg.path.toString(), req.files.headerImg.path.toString()])
.then(function (postedFiles) {
dataObject.iconImg = postedFiles.body.payload.files[0].id;
dataObject.headerImg = postedFiles.body.payload.files[1].id;
//save dataObject after storing images and processing data
dataObject.save(function(savedDataObject){
next(success(req, 200, 'dataObject Saved ' + savedDataObject.id));
});
})
.catch(function(err){
console.log('FAILED: ', err.stack);
return next(failure(req, 500, err));
});
});
When I test my route with a separate small requestJS script, it works just fine:
HTTP rest api request test with requestJS
postDataObject.js
var request = require('request');
var fs = require('fs');
var uuid = require('uuid');
var formData = {
name: 'someName',
info: 'Some INFO and text description. ',
'usersArray[0][uuid]': uuid.v4().toString(),
'usersArray[1][uuid]': uuid.v4().toString(),
'usersArray[2][uuid]': uuid.v4().toString(),
// handle files
iconImg: fs.createReadStream('/var/tmp/img/iconImg.png'),
headerImg: fs.createReadStream('/var/tmp/img/headerImg.png')
};
request.post({url:'http://127.0.0.1:2233/api/postDataObject', formData: formData}, function (err, httpResponse, body) {
if (err) {
return console.error('failed:', err);
}
console.log('DataObject creation is successful! Server responded with:', body);
});
Now I'm writing the wrapper library for the fronted usage, when I use the same code in another context, it seems, that Multer handling req.files.headerImg.path is not working, it's undefined.
The code I use for wrapper library:
wrapper-lib.js
var request = require('request'),
URI = require('URIjs'),
fs = require('fs'),
uuid = require('uuid'),
path = require('path'),
Promise = require('bluebird'),
_ = require('lodash'),
DataObjectBindings.prototype.createDataObject = function (jsonRequestJSFormData) {
var self = this;
// this give the URL of the API to make requests to
return self.getAPIurlHelper().then(function (apiUrl) {
return new Promise(function (resolve, reject) {
request.post({url: apiUrl, form: jsonRequestJSFormData}, function (err, res, body) {
if (err) {
reject(err);
} else {
resolve({res: res, body: JSON.parse(body)});
};
}); //end of .post
}); // end of Promise
}); // end of getAPIurlHelper() function
}; // end of createDataObject function definition
And Finally I test the warpper with:
wrapper-test.js
// Instantiate Broker Client
var Wrapper = require('./wrapper-lib');
var wi; //wrapper instalnce
var ConnectApiRequestTracer = require('./connectApiRequestTracer');
var fs = require('fs');
ConnectApiRequestTracer().connect()
.then(function () {
wi = new Wrapper();
return wi.createDataObject(
uuid.v4(),
{
name: 'Some Cool Name',
info: 'Some nice description and info. ',
'usersArray[0][uuid]': uuid.v4().toString(),
'usersArray[1][uuid]': uuid.v4().toString(),
'usersArray[2][uuid]': uuid.v4().toString(),
iconImg: fs.createReadStream('/var/tmp/img/iconImg.png'),
headerImg: fs.createReadStream('/var/tmp/img/headerImg.png'),
);
})
.then(function (data) {
console.log('SUCCESS: ', data);
})
.catch(function (err) {
console.log('FAILED', err.stack);
});
When I run the test case wrapper-test.js, it throws me an error, that says the req.files.iconImg.path is undefined.
Any ideas what can be wrong?
try using :
req.file.iconImg.path
req.file.headerImg.path
instead of req.files.iconImg.path and req.files.headerImg.path