Node.js - Testing AWS with Mocha


super stack

I'm having trouble writing a test for the following code nodejsusing AWSand graphicsmagick. I've also tried searching for examples on how to write tests for asyncthe waterfallmethod , but no clear results.

// dependencies
var async = require('async');
var AWS = require('aws-sdk');
var gm = require('gm').subClass({ imageMagick: true });
var util = require('util');

// get reference to S3 client
var s3 = new AWS.S3();

exports.AwsHandler = function(event, context) {
// Read options from the event.
console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));
var srcBucket = event.Records[0].s3.bucket.name;
var srcKey = event.Records[0].s3.object.key;
var dstnKey = srcKey;


// Infer the image type.
var typeMatch = srcKey.match(/\.([^.]*)$/);
if (!typeMatch) {
    console.error('unable to infer image type for key ' + srcKey);
    return;
}

var imageType = typeMatch[1];

if (imageType != "jpg" && imageType != "png") {
    console.log('skipping non-image ' + srcKey);
    return;
}

//Download the image from S3, transform, and upload to same S3 bucket but different folders.
async.waterfall([
        function download(next) {
            // Download the image from S3 into a buffer.

            s3.getObject({
                    Bucket: srcBucket,
                    Key: srcKey
                },
                next);
        },

        function transformSave(response, next) {

            var _buffer = null;

            for (var i = 0; i<len; i++) {

                // Transform the image buffer in memory.
                gm(response.Body, srcKey)
                    .resize(_sizesArray[i].width)
                    .toBuffer(imageType, function(err, buffer) {
                        if (err) {
                            next(err);
                        } else {
                            console.log(buffer);
                            _buffer = buffer;
                        }
                    });

                // put newly resized image into respective folder
                s3.putObject({
                    Bucket: srcBucket,
                    Key: "dst/" + _sizesArray[i].destinationPath + "/" + dstnKey,
                    Body: _buffer,
                    ContentType: response.ContentType
                }, next);
            }
        },

    ], function (err) {
        if (err) {
            console.error(
                '---->Unable to resize ' + srcBucket + '/' + srcKey +
                ' and upload to ' + srcBucket + '/dst' +
                ' due to an error: ' + err
            );
        } else {
            console.log(
                '---->Successfully resized ' + srcBucket +
                ' and uploaded to ' + srcBucket + "/dst"
            );
        }

        context.done();
    }
);

}; So far my tests for this module:

require('blanket')({
    pattern: function (filename) {
        return !/node_modules/.test(filename);
    }
});

// in terminal, type the following command to get code coverage: mocha -R html-cov > coverage.html

var chai = require('chai');
var sinonChai = require("sinon-chai");
var expect = chai.expect;
var sinon = require('sinon');
chai.use(sinonChai);
var sync = require("async");

var proxyquire = require('proxyquire');



describe('Image Resizing module', function () {
    var gmSubclassStub = sinon.stub();
    var getObjectStub = sinon.stub();
    var putObjectSpy = sinon.spy();

    var testedModule = proxyquire('../index', {
        'gm': {subClass: sinon.stub().returns(gmSubclassStub)},
        'AWS': {
            "s3": {
                getObject: sinon.stub().returns(getObjectStub),
                putObject: putObjectSpy
            }
        }
    });

   describe('AwsHandler', function () {

        var event = {
            "Records": [
            {
                "s3": {
                    "bucket": {
                        "name": "testbucket"
                    },
                    "object": {
                        "key": "test.jpg"
                    }
                }
            }
        ]
        };


        it("should call gm write with correct files", function () {
            // Arrange


            // Spies are the methods you expect were actually called
            var buffer800Spy = sinon.spy();
            var buffer500Spy = sinon.spy();
            var buffer200Spy = sinon.spy();
            var buffer45Spy = sinon.spy();

            // This is a stub that will return the correct spy for each iteration of the for loop
            var resizeStub = sinon.stub();
            resizeStub.withArgs(800).returns({toBuffer: buffer800Spy});
            resizeStub.withArgs(500).returns({toBuffer: buffer500Spy});
            resizeStub.withArgs(200).returns({toBuffer: buffer200Spy});
            resizeStub.withArgs(45).returns({toBuffer: buffer45Spy});


            // Stub is used when you just want to simulate a returned value
            var nameStub = sinon.stub().yields({"name": "testbucket"});
            var keyStub = sinon.stub().yields({"key": "test.jpg"});
            gmSubclassStub.withArgs(event).returns({resize:resizeStub});
            getObjectStub.withArgs(event).yields({name: nameStub}, {key: keyStub});

            // Act - this calls the tested method
            testedModule.AwsHandler(event);

            // Assert

        });
    });
});
Ivan Fraixedes

It's hard to answer that kind of question here. This question is not very specific nor is it an open-ended question that can be answered with opinions, ideas, etc.

So I created a similar implementation to solve this async.waterfallproblem and provide a test to test AwsHandlerwith 100% coverage .

The code is in this gist because it is more convenient and readable here than here .

I also wrote a blog post related to this implementation

Related


Node.js Mocha testing restful API endpoints and code coverage

KJ3 I've always loved Istanbul and have also tried other Node.js overlay libraries, but I'm running into a problem. Almost all of my unit tests are HTTP calls to APIs like this: it('should update the customer', function (done) { superagent.put('htt

Node.js - Testing AWS with Mocha

super stack I'm having trouble writing a test for the following code nodejsusing AWSand graphicsmagick. I've also tried searching for examples on how to write tests for asyncthe waterfallmethods of , but with no clear results. // dependencies var async = requi

Ajax Testing with Mocha - Node.js

Ballanf I try to use Mocha to write tests for one of my apps. I can run different scenarios when the page is reloaded. Consider the following 1) The user enters a value in the "Username" text field 2) Click the "Save" button 3) This will send an ajax call to s

Unit testing private functions with mocha and node.js

fstab: I am using Mocha in order to unit test an application written for node.js I would like to know if it is possible to unit test unexported functions in modules. example: I define a lot of functions in itfoobar.js function private_foobar1(){ ... } fun

Testing errors thrown in node.js with Mocha Chai

Kira I'm new to node.js and having trouble setting up a simple unit test for a function I want to throw an error. My function is simple: const which_min = function(array) { var lowest = 0; for (var i = 1; i < array.length; i++) { if (array[i] < arr

Node.js Mocha testing restful API endpoints and code coverage

KJ3 I've always loved Istanbul and have also tried other Node.js overlay libraries, but I'm running into a problem. Almost all of my unit tests are HTTP calls to APIs like this: it('should update the customer', function (done) { superagent.put('htt

Testing errors thrown in node.js with Mocha Chai

Kira I'm new to node.js and having trouble setting up a simple unit test for a function I want to throw an error. My function is simple: const which_min = function(array) { var lowest = 0; for (var i = 1; i < array.length; i++) { if (array[i] < arr

Typescript Mocha and AWS testing

mbspark This is my first time trying the Mocha/Chai test. I have an IaC project and before it starts, I want to verify that the secrets stored in the secrets manager actually exist before starting work. when i run this. I just get the output0 passing (0ms) Cod

Testing JS exceptions with Mocha/Chai

Delcho Tried to test some code that throws an exception in Mocha/Chai with no luck, here is the simple code I am trying to test: class window.VisualizationsManager test: -> throw(new Error 'Oh no') Here is my test: describe 'VisualizationsManager', ->

Nested in a for loop in Node.js with the Mocha testing framework

Whitfern I'm in a test where I need nested for loops, but I'm getting lost in the whole async aspect. Basically what's happening now is that I'm going to loop through the array and use the values one by one and log the output. What is currently happening is th

Unit testing of private functions with Mocha and Node.js

fstab I use Mocha to unit test an application written for Node.js. I would like to know if it is possible to unit test unexported functions in modules. example: I define a lot of functions like this in foobar.js: function private_foobar1(){ ... } function

Node.js - Testing AWS with Mocha

super stack I'm having trouble writing a test for the following code nodejsusing AWSand graphicsmagick. I've also tried searching for examples on how to write tests for asyncthe waterfallmethod , but no clear results. // dependencies var async = require('async

Ajax Testing with Mocha - Node.js

Ballanf I try to use Mocha to write tests for one of my apps. I can run different scenarios when the page is reloaded. Consider the following 1) The user enters a value in the "Username" text field 2) Click the "Save" button 3) This will send an ajax call to s

Testing angularjs modules with Mocha in node

Redev mymodule.js is defined as: angular.module('mymodule', []).factory('MyModule', function () { /* my code */ }); Then, I have a mocha test script (test.js) that looks like this: var chai = require('chai'); chai.use(require("chai-as-promised")); var angular

Unit testing private functions with mocha and node.js

fstab: I am using Mocha in order to unit test an application written for node.js I would like to know if it is possible to unit test unexported functions in modules. example: I define a lot of functions in itfoobar.js function private_foobar1(){ ... } fun

Testing errors thrown in node.js with Mocha Chai

Kira I'm new to node.js and having trouble setting up a simple unit test for a function I want to throw an error. My function is simple: const which_min = function(array) { var lowest = 0; for (var i = 1; i < array.length; i++) { if (array[i] < arr

Testing errors thrown in node.js with Mocha Chai

Kira I'm new to node.js and having trouble setting up a simple unit test for a function I want to throw an error. My function is simple: const which_min = function(array) { var lowest = 0; for (var i = 1; i < array.length; i++) { if (array[i] < arr

Node.js Mocha testing restful API endpoints and code coverage

KJ3 I've always loved Istanbul and have also tried other Node.js overlay libraries, but I'm running into a problem. Almost all of my unit tests are HTTP calls to APIs like this: it('should update the customer', function (done) { superagent.put('htt

Testing errors thrown in node.js with Mocha Chai

Kira I'm new to node.js and having trouble setting up a simple unit test for a function I want to throw an error. My function is simple: const which_min = function(array) { var lowest = 0; for (var i = 1; i < array.length; i++) { if (array[i] < arr

Testing errors thrown in node.js with Mocha Chai

Kira I'm new to node.js and having trouble setting up a simple unit test for a function I want to throw an error. My function is simple: const which_min = function(array) { var lowest = 0; for (var i = 1; i < array.length; i++) { if (array[i] < arr

Testing angularjs modules with Mocha in node

Redev mymodule.js is defined as: angular.module('mymodule', []).factory('MyModule', function () { /* my code */ }); Then, I have a mocha test script (test.js) that looks like this: var chai = require('chai'); chai.use(require("chai-as-promised")); var angular