节点:无法模拟aws-sdk方法

时间:2019-05-20 21:11:29

标签: node.js amazon-web-services unit-testing jestjs aws-sdk

我已经尝试了很多在互联网上发现的关于模拟aws-sdk服务的方法,但是没有一种方法对我有用,我什至尝试了模块aws-sdk-mock,但这种方法不起作用,我认为这是因为我没有在函数处理程序中使用aws-sdk

我将jest用作测试运行程序和断言,因此我现在拥有的代码如下:

test.js

const aws = require('aws-sdk-mock');
const Admin = require('./../../../serverless/entities/Admin');

describe('Entity - Admin test', () => {
  jest.spyOn(aws.CognitoIdentityServiceProvider.prototype, 'listUsersInGroup', () => {
    return {
      promise: Promise.resolve({ foo: 'bar' })
    };
  });

  const data = Admin.getListOfUsers();

  console.log(data);
});

Admin.js

/**
 * Admin entity class
 * This class should help managing all super user actions that are required for the sportstracker's application
 * Amazon services used by this entity:
 *  - Cognito (User Pool)
 * Required IAM Policy actions:
 *  - cognito-idp:ListUsersInGroup
 *  - cognito-idp:ListUsers
 *  - cognito-idp:AdminCreateUser
 *  - cognito-idp:AdminDeleteUser
 *  - cognito-idp:AdminGetUser
 *  - cognito-idp:AdminListGroupsForUser
 *  - cognito-idp:AdminUpdateUserAttributes
 *  - cognito-idp:AdminRemoveUserFromGroup
 */

const aws = require('aws-sdk');
const User = require('./../lib/User');
const cognito = new aws.CognitoIdentityServiceProvider();
const UserPoolId = process.env['COGNITO_USER_POOL_ID'];

const rolesMap = {
  admin: 'SuperUser',
  member: 'Member'
};

/**
 * @typedef UsersList
 * @property {Array<UserObject>} members - The list of members
 * @property {Array<UserObject>} admins - The list of admins
 */

class Admin {
  /**
   * Gets a list of users for both admin and members.
   * This executes 2 methods for aws.cognito [admin, member]
   * @returns {Promise<UsersList>} - The object containing the list of members and admins
   */
  static async getListOfUsers () {
    const operations = [
      cognito.listUsersInGroup({ UserPoolId, GroupName: rolesMap.admin }).promise(),
      cognito.listUsersInGroup({ UserPoolId, GroupName: rolesMap.member }).promise()
    ];

    const results = await Promise.all(operations);

    return {
      admins: results[0].Users.map(user => User.mapUserData(user)),
      members: results[1].Users.map(user => User.mapUserData(user))
    };
  }

  ...
}

module.exports = Admin;

我收到此代码的错误是:

TypeError: Cannot read property 'prototype' of undefined

这是因为在调用构造函数之前,sdk中所有服务的原型都没有定义的方法,而且我明白了为什么他们创建了像aws-sdk-mock这样的模块,但是即使该模块也没有帮助我,所以怎么办我提供了在非功能Lambda处理程序中模拟aws服务的正确方法?

2 个答案:

答案 0 :(得分:0)

要在Haplotype中模拟第三方程序包,可以在与jest相同级别的目录中创建一个__mocks__目录,其中将包含模拟函数。

例如,

node_modules

您的. ├── README.md ├── __mocks__ └── aws-sdk.js ├── jest.config.js ├── node_modules ├── package.json ├── src └── yarn.lock 模拟文件可以包含以下内容:

aws-sdk.js

答案 1 :(得分:0)

这个对我有用

const AWS = require('aws-sdk');
jest.mock('aws-sdk');
    
AWS.CognitoIdentityServiceProvider.prototype.listUsers = jest.fn().mockReturnValue({
      promise: jest.fn().mockResolvedValue({})
    });