NodeJS:aws-sdk 的模拟承诺

NodeJS: Mock promise of aws-sdk

我目前正在使用 NodeJS 编写一些代码。

我的代码如下所示:

const AWS = require('aws-sdk');
const PARAMS_ACCOUNT = {
  AttributeNames: [
     "max-instances"
  ]
 };

const ec2 = new AWS.EC2();
const getAccountAttributes = ec2.describeAccountAttributes(PARAMS_ACCOUNT).promise();

function maxInstances() {
    return getAccountAttributes.then(data => {
        return  data.AccountAttributes[0].AttributeValues[0].AttributeValue;
    });
 }

我尝试在 chaiJSmochaJS 旁边使用 aws-sdk-mock,但我不确定如何模拟 [=16= 的 .promise() ].

我的尝试如下所示:

const chai = require('chai');
const mocha = require('mocha');
const awsSDK = require('aws-sdk');
const aws = require('aws-sdk-mock');
const server = require('../instance_limit.js');

const expect = chai.expect;

describe('Sample test', () => {
 it('this is also a test', () => {
  aws.mock('EC2','describeAccountAttributes',function (params, callback){
    callback(null, {AccountAttributes:[{AttributeValues:[{AttributeValue: 10}]}]});
  });
  var awsEC2 = new awsSDK.EC2();
   const instances = server.maxInstances();
   expect(instances).to.equal(10);
  });
});

但是我无法模拟 aws-sdk 调用。 感谢您的帮助。

我能够通过使用依赖注入的原理来解决这个问题,在这种情况下可以防止模拟aws sdk,因为有必要稍微调整我的函数并设置一个默认值。 现在看起来像这样:

const AWS = require('aws-sdk');
const PARAMS_ACCOUNT = {
  AttributeNames: [
 "max-instances"
  ]
 };

const ec2 = new AWS.EC2();
const getAccountAttributes = ec2.describeAccountAttributes(PARAMS_ACCOUNT).promise();

function maxInstances(accountAttributes = getAccountAttributes()) {
    return accountAttributes.then(data => {
        return data.AccountAttributes[0].AttributeValues[0].AttributeValue;
    });
}

这现在允许我在测试期间提供示例值,如下所示:

const chai = require('chai');
const mocha = require('mocha');
const server = require('../instance_limit.js');

const expect = chai.expect;

describe('data calculation based on ec2 values', () => {
 it(' expects to return max Instances value equal 10', () => {
   const accountAttributeObject = {AccountAttributes:[{AttributeValues:[{AttributeValue: 10}]}]}
   const accountAttributes = Promise.resolve(accountAttributeObject);
   const instances = server.maxInstances(accountAttributes);

   return instances.then( data => {
     expect(data).to.equal(10);
   });
  });
})