Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking promise from DynamoDB Documentclient

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()

    })
})
like image 988
Wollzy Avatar asked Mar 15 '19 19:03

Wollzy


1 Answers

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]});
        });
  })
})
like image 93
Deiv Avatar answered Oct 18 '22 20:10

Deiv