0

I am trying to mock SQS call defined in my file.js. It is a global instance in the file. So, while testing as I have to require file.js, its instance is set and my mock method is not called. However, if I set that SQS instance locally in the function inside which it is required, I am able to mock. But that would be wrong as that instance will be set every time that method is called. How can I mock SQS in my test? I have tried all the ways which were given there in the issues. None of them is working for me.

//file.js

const AWS = require('aws-sdk');
const sqs = new AWS.SQS();
const queueURL = config.sqs_connect.queue_url;
const params = {
    MaxNumberOfMessages: 10,
    QueueUrl: queueURL
};
exports.receiveMessages = async function () {
    // let sqs = new AWS.SQS();
    return new Promise((resolve, reject) => {
        sqs.receiveMessage(params, function (err, data) {
        if (err) {
            console.log("error")
            reject(err);
        } else if (data.Messages) {
            try {
                consumeAndDeleteMessages(data.Messages, err => {
                    if (err) reject(err);
                    else resolve();
                });
            } catch (error) {
                reject(error);
            }
        } else {
            // logger.log("No data in queue");
            resolve();
        }
    });
})
} 

// file.test.js

const AWS = require('aws-sdk');
const consumer = require('path-to-file');

describe("foo", () => {
 it("updates all info", async () => {
    let delete_stack = [];
    AWSMock.setSDKInstance(AWS);
    AWSMock.mock('SQS', 'receiveMessage', (params, callback) => {
        callback(null, { Messages: [{ MessageId: '1234', ReceiptHandle: 'qwertyu', Body: JSON.stringify(update_payload) }] });
    });
    AWSMock.mock('SQS', 'deleteMessageBatch', (params, callback) => {
        delete_stack.push(params.Entries);
        callback(null, {});
    });

    await consumer.receiveMessages();
    AWSMock.restore('SQS');
    expect(delete_stack).toStrictEqual([
        [{ "Id": "1234", "ReceiptHandle": "qwertyu" }]
    ]);
});
}); 

If I define sqs locally in receiveMessage, the test will work file. I have tried all the ways provided, none of them is working. Am I doing something wrong?

Utkarsh Vaish
  • 48
  • 1
  • 10

0 Answers0