aws-sdk-mock 模拟 s3.putBucketPolicy 不起作用

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

我有这个功能想测试一下。

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
      }
    });
  });
}

我想怎么测试:

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');

    });
  });
});

问题是 returns [ExpiredToken:提供的令牌已过期。] 因为模拟本身不起作用,它会尝试退出互联网并执行 s3.putBucketPolicy 功能。

我是新手。我应该怎么做才能让它发挥作用?

doc.

所述,您需要在测试方法中初始化S3客户端

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.