javascript - Mock code in another module -
i want mock amazon aws s3 getobject
the code want test following one: in helper.js
var aws = require('aws-sdk'); var s3 = new aws.s3(); exports.get_data_and_callback = function(callback, extra){ s3.getobject( {bucket: src_bucket, key: src_key}, function (err, data) { if (err != null) { console.log("couldn't retrieve object: " + err); }else{ console.log("loaded " + data.contentlength + " bytes"); callback(data, extra); } }); }
in test/helper_test.js
i wrote test should mock module aws
var assert = require('assert'); var mockery = require('mockery'); describe("helper", function() { it('loads , returns data s3 callback', function(){ mockery.enable(); var fakeaws = { s3: function(){ return { getobject: function(params, callback){ callback(null, "hello") } } } } mockery.registersubstitute('aws-sdk', fakeaws); function replace_function(err, data){ console.log(data); } require('../helper.js').get_data_and_callback(replace_function, null); }); });
when require aws in test-file test/helper_test.js
this:
aws = require('aws-sdk'); s3 = new aws.s3; s3.getobject(replace_function)
then code works, prints out hello
.
but execution of require('../helper.js').get_data_and_callback(replace_function, null);
doesn't work expected, aws stays same not replaced fakeaws. wrong? maybe have other solutions replace s3 thanks
we have created aws-sdk-mock npm module mocks out aws sdk services , methods. https://github.com/dwyl/aws-sdk-mock
it's easy use. call aws.mock service, method , stub function.
aws.mock('s3', 'getobject', function(params, callback) { callback(null, 'success'); });
then restore methods after tests calling:
aws.restore('s3', 'getobject');
this works every service , method in as-sdk.
Comments
Post a Comment