Nodejs - 测试AWS与摩卡 [英] Nodejs - testing AWS with Mocha

查看:309
本文介绍了Nodejs - 测试AWS与摩卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法编写测试以下 nodejs code,它使用 AWS 实:graphicsmagick 。我试图寻找的例子还对如何编写测试异步瀑布的方法,但没有任何明确的结果

  //依赖
VAR异步=需要('异步');
VAR AWS =需要('AWS-SDK);
变种克=需要('克')的子类({ImageMagick的:真})。
VAR UTIL =需要('UTIL');

//获取引用S3客户端
VAR S3 =新AWS.S3();

exports.AwsHandler =函数(事件上下文){
//读取从事件的选项。
的console.log(读从事件选项:\ N,util.inspect(事件,{深度:5}));
变种srcBucket = event.Records [0] .s3.bucket.name;
变种srcKey = event.Records [0] .s3.object.key;
VAR dstnKey = srcKey;


//推断出图像类型。
VAR typeMatch = srcKey.match(/\.([^.]*)$/);
如果(!typeMatch){
    console.error('无法推断出图像类型键+ srcKey);
    返回;
}

变种IMAGETYPE = typeMatch [1];

如果(IMAGETYPE =JPG和放大器;!&安培;!IMAGETYPE =PNG){
    的console.log('跳过非图像'+ srcKey);
    返回;
}

//从S3下载图像,转换和上传到相同的S3存储桶,但不同的文件夹。
async.waterfall([
        功能下载(下){
            //下载从S3图像到缓冲区中。

            s3.getObject({
                    铲斗:srcBucket,
                    重点:srcKey
                },
                下一个);
        },

        功能transformSave(响应,下一个){

            VAR _buffer = NULL;

            对于(VAR I = 0; I< LEN;我++){

                //变换图像缓冲存储器中。
                通用汽车公司(response.Body,srcKey)
                    .resize(_sizesArray [I] .WIDTH)
                    .toBuffer(IMAGETYPE,功能(ERR,缓冲区){
                        如果(ERR){
                            下一个(ERR);
                        } 其他 {
                            的console.log(缓冲液);
                            _buffer =缓冲区;
                        }
                    });

                //把新调整后的图像到各自的文件夹中
                s3.putObject({
                    铲斗:srcBucket,
                    键:DST /+ _sizesArray [I] .destinationPath +/+ dstnKey,
                    身体:_buffer,
                    的ContentType:response.ContentType
                }, 下一个);
            }
        },

    ],功能(错误){
        如果(ERR){
            console.error(
                ---->无法调整+ srcBucket +/+ srcKey +
                并上传至+ srcBucket +'/ DST'+
                由于出现错误:+ ERR
            );
        } 其他 {
            的console.log(
                ---->成功调整+ srcBucket +
                并上传至+ srcBucket +/ DST
            );
        }

        context.done();
    }
);
 

}; 我对这个模块的测试至今:

 规定('毯子')({
    模式:功能(文件名){
        返回/node_modules/.test(文件名)!;
    }
});

//在终端,键入以下命令来获得code范围:摩卡-R HTML-COV> coverage.html

VAR柴=需要('柴');
VAR sinonChai =要求(兴农钗);
VAR预计= chai.expect;
VAR兴农=需要('兴农');
chai.use(sinonChai);
VAR同步=需要(异步);

VAR proxyquire =需要('proxyquire');



描述(图像大小调整模块',函数(){
    变种gmSubclassStub = sinon.stub();
    变种getObjectStub = sinon.stub();
    变种putObjectSpy = sinon.spy();

    VAR testedModule = proxyquire('../指数',{
        通用汽车:{子类:sinon.stub()返回(gmSubclassStub)},
        AWS:{
            S3:{
                的getObject:sinon.stub()返回(getObjectStub)
                putObject:putObjectSpy
            }
        }
    });

   描述(AwsHandler',函数(){

        VAR事件= {
            纪录:
            {
                S3:{
                    桶: {
                        名:testbucket
                    },
                    目的: {
                        钥匙:test.jpg放在
                    }
                }
            }
        ]
        };


        它(应该叫克写有正确的文件,函数(){
            // 安排


            //间谍是你期望实际上是调用的方法
            变种buffer800Spy = sinon.spy();
            变种buffer500Spy = sinon.spy();
            变种buffer200Spy = sinon.spy();
            变种buffer45Spy = sinon.spy();

            //这是一个存根将返回正确的间谍的每次迭代循环
            变种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});


            当你只是想模拟返回值//存根使用
            VAR nameStub = sinon.stub()产量({名:testbucket});
            。VAR keyStub = sinon.stub()产量({关键:test.jpg放在});
            gmSubclassStub.withArgs(事件).returns({调整:resizeStub});
            getObjectStub.withArgs(事件).yields({名称:nameStub},{关键:keyStub});

            //法案 - 这要求测试方法
            testedModule.AwsHandler(事件);

            // 断言

        });
    });
});
 

解决方案

这是很难应对这样的问题在这里;这个问题是不是很具体,它不是能与意见,想法,等来回答一个悬而未决的问题。

因此​​,我创建了一个类似的实现,它解决了 async.waterfall 问题,并提供了一​​个测试,测试 AwsHandler 100%的覆盖​​率。

在code是在此要点,因为它更方便和可读性为比这里那里。

我也写一个的博客文章与此相关的实施

I'm having trouble writing the tests for the following nodejs code which uses AWS and graphicsmagick. I have tried to search for examples also on how to write tests for async's waterfall method but without any definite 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();
    }
);

}; My tests for this module so far:

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

        });
    });
});

解决方案

It's hard to respond this kind of question here; the question is not very specific and it's not an open question which can be replied with opinions, thoughts, etc.

Hence, I've created an similar implementation which solve the async.waterfall issue and provide a test which test the AwsHandler with 100% coverage.

The code is in this gist, because it's more handy and readable to be there than here.

I've also written a blog post related with this implementation

这篇关于Nodejs - 测试AWS与摩卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆