0

我的 Hapi.Js 服务器中有文件上传 POST 点。这是代码:

 server.route([{
 method: 'PUT',
 path: '/upload/{id}',
 config: {
     handler: function(req,res) {
         async.waterfall([
             function checkEntityInDbExists(req.params.id,callback) {
                 ...
                 callback(null, entityId);
             },
             function uploadPictureToAWS(entityId, callback) {
                 ...
                 callback(null, imageLink);
             },
             function savePictureLinkInDbEntity(entityId, callback) {
                 ...
                 callback(null, imageLink);
             }
         ], function(err, result) {
             if (err) {
                 return reply(err);
             }
             return reply(result);
         });
     }
 }

}]);

如何正确覆盖此代码/点的“应返回上传的图像路径”的情况,而不会触及 DB 和 AWS?

4

1 回答 1

1

我认为您可能需要诸如proxyquire 之类的包来帮助您模拟方法并使它们返回有效结果,以便您的逻辑可以继续。

示例用法(来自Async-Hapi-Test-Example):

var assert = require("assert");
var chai = require("chai");
var sinon = require("sinon");
var sinonChai = require("sinon-chai");
var proxyquire = require("proxyquire").noCallThru();
var expect = chai.expect;

chai.should();
chai.use(sinonChai);

describe("Testing route index", function() {
    var sut;
    var db;
    var aws;
    beforeEach(function() {
        db = {
            check: sinon.spy(),
            savePic: sinon.spy(function(){ return "a link?"; })
        }
        aws = {
            upload: sinon.spy()
        }
        sut = proxyquire('./index', {"./db": db, "./aws": aws});
    });

    describe("upload", function() {
        it("should pass", function(done){
            var request = {
                params: {
                    id: 9001
                }
            }
            var reply = function(results) {
                results.should.equal('a link?');
                db.check.should.been.calledOnce;
                db.savePic.should.been.calledOnce;
                aws.upload.should.been.calledOnce;
                done();
            }
            sut[0].config.handler(request, reply);
        });
    });
});
于 2016-02-15T15:43:41.817 回答