Search code examples
javascriptamazon-s3jestjsaws-sdk-mock

aws-sdk-mock mocking an s3.putBucketPolicy does not work


I have this function which I want to test.

async function PutBucketPolicy(putBucketPolicyParams) {
  logger.debug("---- PutBucketPolicy");
  return new Promise(async(resolve, reject) => {

    s3.putBucketPolicy(putBucketPolicyParams, function(err, data) {
      if (err)
      {
        resolve(err);
        logger.debug("Error occured!");
        logger.debug(err, err.stack); // an error occurred
      }
      else
      {
        resolve(data);
        logger.debug("Data: ", data);
        logger.debug(data); // successful response
      }
    });
  });
}

How I want to test it:

describe("Testing PutBucketPolicy function", () => {
  describe("when called with a valid bucket policy object and an event then it", () => {
    it("sets the bucket policy through an aws call.", async() => {

      AWSMock.mock("S3","putBucketPolicy",{ "Body": Buffer.from("somestring") });

      const result = await PutBucketPolicy(helper.putBucketPolicyParams);
      expect( result).toMatchObject(helper.resultPolicyObject);

      AWSMock.restore('S3');

    });
  });
});

The problem is that it always returns that [ExpiredToken: The provided token has expired.] as the mocking itself would not work and it tries to go out the internet and execute the s3.putBucketPolicy function.

I'm new to this. What should I do to make it work?


Solution

  • You need to initialise the S3 client inside the method to test, as mentioned in the doc.

    NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked e.g for an AWS Lambda function example 1 will cause an error region not defined in config whereas in example 2 the sdk will be successfully mocked.

    Example 1:

    const AWS      = require('aws-sdk');
    const sns      = AWS.SNS();
    const dynamoDb = AWS.DynamoDB();
    
    exports.handler = function(event, context) {
      // do something with the services e.g. sns.publish
    }
    

    Example 2

    const AWS = require('aws-sdk');
    
    exports.handler = function(event, context) {
      const sns      = AWS.SNS();
      const dynamoDb = AWS.DynamoDB();
      // do something with the services e.g. sns.publish
    }
    

    Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either.