dwyl / aws-sdk-mock

:rainbow: AWSomocks for Javascript/Node.js aws-sdk tested, documented & maintained. Contributions welcome!
Apache License 2.0
1.09k stars 107 forks source link

mock not working inside lambda function #119

Open stephen1706 opened 6 years ago

stephen1706 commented 6 years ago

So i'm trying to use aws-sdk-mock to mock the calling of a dynamo db and cognito. But it turns out I always fail to mock although when it is called inside the .test.js file is fine. but inside the real lambda function it always call the real function. here is the code:

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);
            }
        });
    });
};
HRX-Arvin commented 6 years ago

I meet the same problem