打字稿摩卡和AWS测试

时间:2020-03-14 00:09:39

标签: typescript mocha chai

这是我第一次在Mocha / Chai中进行测试。我有一个IaC项目,在启动之前,我想在执行工作之前验证存储在Secrets Manager中的秘密是否确实存在。

运行此命令时。我只是得到输出0 passing (0ms)

代码:该代码获取跨区域的凭据,然后如果该机密由于不比较expect.to.equal

中的字符串而退出,则应进行比较。
import * as awsSdk from 'aws-sdk';
import { expect } from 'chai';
import { secretValues } from './config';

// Assume Role
const sts = new awsSdk.STS();

// Function to Update Credentials
const getCrossAccountCredentials = async (account: string, role: string) =>
  new Promise((resolve, reject) => {
    const timestamp = new Date().getTime();
    const params = {
      RoleArn: `arn:aws:iam::${account}:role/${role}`,
      RoleSessionName: `sts-session-${timestamp}`
    };
    sts.assumeRole(params, (err, data) => {
      if (err) reject(err);
      else {
        resolve({
          accessKeyId: data.Credentials.AccessKeyId,
          secretAccessKey: data.Credentials.SecretAccessKey,
          sessionToken: data.Credentials.SessionToken
        });
      }
    });
  });

// Run Test for Secrets Manager
describe('# Secrets Manager Tests:', () => {
    secretValues.map(async dir => {
        // Configure the AWS SDK with the correct region
        awsSdk.config.update({
        region: dir.region
        });

        // Get Assume Role
        const accessparams = await getCrossAccountCredentials(
        dir.account,
        dir.role
        );

        // Initialize SecretsManager Client
        const sm = new awsSdk.SecretsManager(accessparams);

        // Set Params for Describe Secret
        const params = {
        SecretId: `ServiceAccounts/${dir.name}/admin`
        };

        // Run Each Account
        it('Should exists in AWS', async ()  => {
            // Describe the Secret
            sm.describeSecret(params, (err, data) => {
                if (err) {
                    throw err;
                }
                else {
                    expect(`${data.Name}`).to.equal(`ServiceAccounts/${dir.name}/admin`);
                }
            });
        }); 
    }); 
}); 

预期行为:

Secrets Manager Tests:
3 of 3 passing

1 个答案:

答案 0 :(得分:0)

我知道了我的问题(尽管我仍然不太了解)

工作代码现在为:

import * as AWS from 'aws-sdk';
import { expect } from 'chai';
import { secretValues } from './config';

// Run Test for Secrets Manager
describe('# Secrets Manager Tests:', () => {    
    config.ad.directories.map( dir => {
        it(`${dir.name} should exist in AWS`, async ()  => {
            // Configure the AWS SDK with the correct region
            AWS.config.update({
                region: config.ad.region
            });

            const sts = new AWS.STS();

            const stsParams = {
                RoleArn: `arn:aws:iam::${dir.account}:role/${config.provider.role}`,
                RoleSessionName: `session-${dir.account}`,
                DurationSeconds: 900
            }

            const assumeRole = await sts.assumeRole(stsParams)
                .promise().then(data => data.Credentials)
                .catch((err) => { console.log(err);})

            const credJSON = JSON.stringify(await assumeRole)
            const creds = JSON.parse(credJSON)

            const smParams = {
                accessKeyId: creds.AccessKeyId,
                secretAccessKey: creds.SecretAccessKey,
                sessionToken: creds.SessionToken
            };

            const sm = new AWS.SecretsManager(smParams);

            // Set Params for Describe Secret
            const params = {SecretId: `ServiceAccounts/${dir.name}/admin`};

            const response = await sm.describeSecret(params).promise()
                .then((data) => data.Name)
                .catch(() => {})  

            expect(await response).to.equal(`ServiceAccounts/${dir.name}/admin`);

        }) // dirMap
    }) // it
}) // describe