aws-sdk-mock在lambda函数中不起作用

时间:2018-03-22 08:04:23

标签: node.js unit-testing aws-lambda aws-sdk aws-sdk-mock

所以我试图用aws-sdk-mock来模拟发电机db和cognito的调用。但事实证明我总是无法模拟,虽然在.test.js文件中调用它是好的。但在真正的lambda函数中,它总是调用真正的函数。这是代码:

describe('User email/phone registration test', function() {
  before(function(){
    AWSMock.mock('DynamoDB.DocumentClient', 'put', function (params, callback){
      console.log("mock called");  
      callback(null, "1234");
    });
  });

  it('should work with valid email and password', function(done) {
      CreateUser("erge","erge","erge"); --> will work, mock is called
      return LambdaTester(register) --> won't work always called the real function
              .event({"email": "haha28@haha.com", "password":"Password01!"})
              .expectResult((result) => {
                  console.log("result: " + JSON.stringify(result));
                  expect(result.statusCode).to.eql(201);
                  let response = JSON.parse(result.body);
                  expect(response.body.accountId).to.exist;
              }).verify(done);
  });

  after(function () {
    AWSMock.restore();
  });
});

const CreateUser = function (userId, email, phoneNumber){
    const docClient = new AWS.DynamoDB.DocumentClient();
    const table = "SSO-User";

    const date = new Date();
    const timestamp = date.toISOString();
    var params = {
        TableName:table,
        Item:{
            userId,
            "email": email,
            "phoneNumber": phoneNumber,
            "createdAt": timestamp,
            "updatedAt": timestamp
        }
    };

    return new Promise((resolve, reject) => {
        docClient.put(params, function(err, data) {
            if (err) {
                reject(JSON.stringify(err, null, 2));
            } else {
                resolve(userId);
            }
        });
    });
};

0 个答案:

没有答案