7

So I'm running some unit tests and I want to essentially stub out the promise so it resolves, or rejects, when I want it to. Here is what my code looks like.

getStatusForPromiseID = async (promiseId, docClient) => { let data = await getStatusfromDB(promiseId, docClient); console.log("data.Items =========>", data.Items); return { "promiseId": data.Items[0].event_id, "status": data.Items[0].STATUS, "errors":data.Items[0].ERRORS } } function getStatusfromDB(promiseId, docClient) { console.log("In getActiveTokenFromDB " + promiseId); var params = { TableName: 'epayments-nonprod-transactions', KeyConditionExpression: 'event_id = :event_id', ExpressionAttributeValues: { ':event_id': promiseId } }; return docClient.query(params).promise(); } 

I would like to mock out docClient.query(params).promise()

Here is what my current test looks like, it runs but when I debug it says the PromiseStatus of resObj is rejected. I'd like to mock it out so I could have values in data.Items to assert.

describe('App function tests', ()=>{ test('getStatusForPromiseID', ()=>{ let docClient = new aws.DynamoDB.DocumentClient() docClient.query.promise = jest.fn() docClient.query.promise.mockImplementation(cb =>{ cb(true, {Items: [1,2,3]}) }) let resObj = getStatusForPromiseID('11011', docClient) expect(docSpy).toHaveBeenCalled() }) }) 

1 Answer 1

6

You can use aws-sdk-mock to mock DynamoDB DocumentClient with a custom response.

To mock a successful response you can do:

AWS.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, {Items: [1, 2, 3]}); }); 

And to mock an error, you can simply do:

AWS.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(new Error("Your error")); }); 

Keep in mind aws-sdk-mock will throw an error automatically if you provide invalid parameters, which is a neat feature.

This will work even if you call .promise() on the SDK call

As per comment, to mock the service for when it is being passed into the function:

var AWS = require("aws-sdk"); var AWS_mock = require("aws-sdk-mock"); describe('App function tests', ()=>{ test('getStatusForPromiseID', ()=>{ AWS_mock.mock('DynamoDB.DocumentClient', 'query', function(params, callback) { callback(null, {Items: [1, 2, 3]}); }); let docClient = new AWS.DynamoDB.DocumentClient(); return getStatusForPromiseID('11011', docClient) .then(result => { expect(result).to.equal({Items: [1, 2, 3]}); }); }) }) 
Sign up to request clarification or add additional context in comments.

2 Comments

How would I write this up since the documentClient is being passed to the function? From my understanding the aws-sdk-mock won't work unless the aws object is being declared inside the function.
Edited my answer to include that scenario. I have personally encountered that test type, so I know this works

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.