0
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 模拟的代码。问题是,我无法模拟 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();
    });
})

任何帮助表示赞赏。

4

0 回答 0