TypeError: sns.publish is not a function , jest mock AWS SNS

I am trying to mock AWS.SNS and I am getting error. I referred posts on StackOverflow and could come up with below. Still, I am getting an error. I have omitted the irrelevant portion. Can someone please help me?

Below is my index.ts

import { SNS } from "aws-sdk";

export const thishandler = async (event: thisSNSEvent): Promise<any> => {

// I have omitted other code that works and not related to issue I am facing. 
// I am receiving correct value of 'snsMessagetoBeSent' I verified that. 

const response = await sendThisToSNS(snsMessagetoBeSent);

} // thishandler ends here

async function sendThisToSNS(thisMessage: snsAWSMessage) {
  const sns = new SNS();
  const TOPIC_ARN = process.env.THIS_TOPIC_ARN;


  var params = {
    Message: JSON.stringify(thisMessage), /* required */
    TopicArn: TOPIC_ARN
  };

  return await sns.publish(params).promise();
}

My test case is below

jest.mock('aws-sdk', () => {
    const mockedSNS = {
      publish: jest.fn().mockReturnThis(),
      promise: jest.fn()
    };

    return {
      SNS: jest.fn(() => mockedSNS),

    };
  });

import aws, { SNS } from 'aws-sdk';

const snsPublishPromise = new aws.SNS().publish().promise;



import { thishandler } from "../src/index";

describe("async testing", () => {
    beforeEach(() => {
        jest.restoreAllMocks();
        jest.resetAllMocks();
    });

it("async test", async () => {

        const ENRICHER_SNS_TOPIC_ARN = process.env.ENRICHER_SNS_TOPIC_ARN;
        process.env.ENRICHER_SNS_TOPIC_ARN = "OUR-SNS-TOPIC";

     const mockedResponseData ={
            "Success": "OK"
        };

        (snsPublishPromise as any).mockResolvedValueOnce(mockedResponseData);

const result = await thishandler(thisSNSEvent);
});

I get error as TypeError: sns.publish is not a function

Answers:

Answer

Here is the unit test solution:

index.ts:

import { SNS } from 'aws-sdk';

export const thishandler = async (event): Promise<any> => {
  const snsMessagetoBeSent = {};
  const response = await sendThisToSNS(snsMessagetoBeSent);
  return response;
};

async function sendThisToSNS(thisMessage) {
  const sns = new SNS();
  const TOPIC_ARN = process.env.THIS_TOPIC_ARN;

  const params = {
    Message: JSON.stringify(thisMessage),
    TopicArn: TOPIC_ARN,
  };

  return await sns.publish(params).promise();
}

index.test.ts:

import { thishandler } from './';
import { SNS } from 'aws-sdk';

jest.mock('aws-sdk', () => {
  const mSNS = {
    publish: jest.fn().mockReturnThis(),
    promise: jest.fn(),
  };
  return { SNS: jest.fn(() => mSNS) };
});

describe('59810802', () => {
  let sns;
  beforeEach(() => {
    sns = new SNS();
  });
  afterEach(() => {
    jest.clearAllMocks();
  });
  it('should pass', async () => {
    const THIS_TOPIC_ARN = process.env.THIS_TOPIC_ARN;
    process.env.THIS_TOPIC_ARN = 'OUR-SNS-TOPIC';

    const mockedResponseData = {
      Success: 'OK',
    };
    sns.publish().promise.mockResolvedValueOnce(mockedResponseData);
    const mEvent = {};
    const actual = await thishandler(mEvent);
    expect(actual).toEqual(mockedResponseData);
    expect(sns.publish).toBeCalledWith({ Message: JSON.stringify({}), TopicArn: 'OUR-SNS-TOPIC' });
    expect(sns.publish().promise).toBeCalledTimes(1);
    process.env.THIS_TOPIC_ARN = THIS_TOPIC_ARN;
  });
});

Unit test results with 100% coverage:

 PASS  src/stackoverflow/59810802/index.test.ts (13.435s)
  59810802
    ? should pass (9ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.446s

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59810802

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.