我想測試此代碼:如何在承諾測試工廠中使用間諜?
'use strict';
var Promise = require('bluebird');
var AWS = require('aws-sdk');
var fs = Promise.promisifyAll(require('fs-extra'));
var path = require('path');
var dispatcher = function() {
return {
/**
* @param {Object} options
* @param {string} options.s3_access_key
* @param {string} options.s3_secret_key
* @param {string} options.s3_bucket
* @param {string} options.file - Path to the file to be uploaded
* @param {string} [options.file_key] - Name to save the file under, defaults to the original file's name
* @returns {Function} Promise - A promise resolved with `true` or rejected with an Error
*/
upload: Promise.method(function upload(options) {
var s3_options = {
accessKeyId: options.s3_access_key,
secretAccessKey: options.s3_secret_key,
params: {
Bucket: options.s3_bucket
}
};
var file_stream = fs.createReadStream(options.file);
var file_key = options.file_key || path.basename(options.file);
var promisedS3 = Promise.promisifyAll(new AWS.S3(s3_options));
return promisedS3.putObjectAsync({
Body: file_stream,
Key: file_key
});
})
};
};
module.exports = {
create: dispatcher
};
我知道該怎麼做集成測試,但我也想驗證promisedS3
被調用用正確的參數。我想我需要使用間諜,但我不知道如何將自己「插入」測試中的promisedS3.putObjectAsync以攔截參數並進行比較。
我想避免用私有方法打包調用S3並繼續使用工廠。
你看過使用sinon嗎? –
我有,但我不知道我完全理解如何從我的代碼中進入'promisedS3'對象。我可以'var spy = sinon.spy(require('./ dispatcher'),'upload');'但我不明白它是如何幫助我窺探'promisedS3.putObjectAsync'調用。 – springloaded
請在對象的原型而不是每個新實例上調用'promisifyAll',這會顯着加快。 –