无法使用proxyquire模拟S3下载请求

时间:2017-11-11 09:19:04

标签: node.js tdd sinon proxyquire

const awsSdk = require('aws-sdk');

module.exports = {

    downloadFile(bucketName, fileName, callback) {
        var s3 = new awsSdk.S3();
        var params = { Bucket: bucketName, Key: fileName };
        var file = require('fs').createWriteStream('abcd.jpg');
        var stream = s3.getObject(params).on('error', function (err) {
            console.log(' download.on');
            callback('error', null);
        })
        .createReadStream()
        stream.pipe(file);
    }
}

上面是我需要使用proxyquire在我的Test类中进行模拟的代码。问题是,我无法模拟像getObject,on,createReadStream这样的方法。此外,在模拟之后,我需要从测试类中发出错误事件,该事件将触发上述on方法,该方法将在测试异常的测试类中调用回调。

以下是我的测试类代码。

const proxyquire = require('proxyquire').noCallThru().noPreserveCache();
const sinon = require('sinon');
const emitter = require('events').EventEmitter;


function Download() {
    emitter.call(this);
    this.error = function () {
        this.emit('error');
    }
}

describe('S3 download test', () => {
    awsSdkMock = {}
    awsSdkMock.config = {};
    awsSdkMock.config.region = { };
    var s3Instance = {};    
    awsSdkMock.S3 = function (){
        return s3Instance;
    };
    var object = {};
    s3Instance.getObject = function (params){ 
        return object; 
    };

    var request = {};
    const errorCallBack = sinon.spy();
    var err = 'error';
    object.on = function (err, errorCallBack) {
        console.log('object.on');  
        errorCallBack();      
        return request;
    };
    var stream = {};
    request.createReadStream = function(){
        console.log('createReadStream');        
        return stream
    };
    stream.pipe = function(file){
        console.log('download.error');
       // download.error();            
    };



    Download.prototype.__proto__ = emitter.prototype;
    var download = new Download();



    const s3 = proxyquire('./../../../modules/s3', {
        'aws-sdk': awsSdkMock
    })


    it('Error in download test', (done) => {
        const errorCallBack = sinon.spy();
        s3.downloadFile('123', 'abcd', errorCallBack);
        sinon.assert.calledWith(errorCallBack, 'error', null);
        done();
    });
})

感谢任何帮助。

0 个答案:

没有答案