NodeJS:模拟aws-sdk的承诺

时间:2018-03-16 07:20:08

标签: node.js mocha chai aws-sdk-js aws-sdk-mock

我目前正在研究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;
    });
 }

我试图在aws-sdk-mockchaiJS旁边使用mochaJS,但我不确定如何模仿.promise() aws-sdk 1}}。

我的尝试如下:

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电话。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

我能够通过使用依赖注入原理解决问题,这种情况可以防止在这种情况下模拟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);
   });
  });
})