2

所以我正在尝试使用 aws-sdk-mock 来模拟 dynamo 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);
            }
        });
    });
};
4

0 回答 0