dwyl / aws-sdk-mock

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

Mocking within promise chains #67

Open ernieay opened 7 years ago

ernieay commented 7 years ago

I have a promise chain that calls two different aws functions sequentially:

var dynamo = new AWS.DynamoDB.DocumentClient();
dynamo.get(params).promise()
.then((data) => {
  ...
  return dynamo.update(params).promise();
}).then(() => {
 ...
}).catch((err) => {
  //I want to mock this error to get to here
});

In my tests I mock them as such:

AWS.mock('DynamoDB.DocumentClient', 'get', function (params, callback) {
  callback(null, { Data : "data" });
});

AWS.mock('DynamoDB.DocumentClient', 'update', function (params, callback) {
  callback({ message: "error" });
});

However, the second function is not mocked - the code calls the real AWS function and I never reach the commented section of my code. The tests/mocks previously worked when the code was written using just callbacks, but has stopped once we refactored to use promises.

Am I using aws-sdk-mock incorrectly, or is this a limitation of the package?

ngocketit commented 7 years ago

I got the same issue.

ngocketit commented 7 years ago

I got it. It was the issue with my test cases. AWS.restore needs to be called once the promise resolves, not before that of course.

ernieay commented 7 years ago

@ngocketit You sir, are a genius.

and I am a fool.

I shall close this issue.

nelsonic commented 7 years ago

@ngocketit thank you very much for remembering to come back and share what you did to make it work! That's really helpful to everyone else using promises in their code. ✅ @ernieay you're no "fool". (don't be so hard on yourself!) 😸

Yay! now... if we could update the Readme (Docs) with a Promises section this would be a great outcome! 😉