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

后端 未结 1 1056
我在风中等你
我在风中等你 2021-01-26 09:15

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 p

相关标签:
1条回答
  • 2021-01-26 09:56

    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

    0 讨论(0)
提交回复
热议问题