javascript - TypeError: sns.publish is not a function , jest mock AWS SNS - Stack Overflow

I am trying to mock AWS.SNS and I am getting error. I referred posts on StackOverflow and could e up wi

I am trying to mock AWS.SNS and I am getting error. I referred posts on StackOverflow and could e 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

I am trying to mock AWS.SNS and I am getting error. I referred posts on StackOverflow and could e 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

Share Improve this question edited Jan 20, 2020 at 3:51 Lin Du 103k136 gold badges334 silver badges567 bronze badges asked Jan 19, 2020 at 14:06 fly.birdfly.bird 1311 gold badge4 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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./mrdulin/jest-codelab/tree/master/src/stackoverflow/59810802

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745298927a4621315.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信