Using spyOn with Jest to mock an AWS SNS publish call

Viewed 435

I'm trying to use spyOn in Jest to mock an AWS SNS publish call. I'm not well versed in AWS's ecosystem, nor am I super experienced with writing Jest tests, so I'm a bit stuck. In the following test code, when spyOn is called for the DynamoDB put method I receive no errors, but when it's called for the SNS publish method, I receive the error that follows. Most of this code was written by someone else, and I'm attempting to follow the same templating for the publish mock.

const lambda = require('../../../src/handlers/sign-up.js');

const dynamodb = require('aws-sdk/clients/dynamodb'); 
const AWS = require("aws-sdk");
AWS.config.update({region: 'us-east-1'})
const sns = new AWS.SNS();

const allowOrigin = process.env.ALLOW_ORIGIN

describe('Test signUpHandler', function () {
    let putSpy; 
    let publishSpy;

    beforeAll(() => { 
        putSpy = jest.spyOn(dynamodb.DocumentClient.prototype, 'put'); 
        publishSpy = jest.spyOn(sns.prototype, 'publish')
    }); 
 

    afterAll(() => { 
        publishSpy.mockRestore();
        putSpy.mockRestore(); 
    });
 

    it('should add email to the table', async () => {
        const returnedItem = { email: 'test@example.com' };
 
        putSpy.mockReturnValue({ 
            promise: () => Promise.resolve(returnedItem) 
        }); 
 
        const event = { 
            httpMethod: 'POST', 
            headers: {
                origin: allowOrigin
            },
            body: '{"email": "test@example.com"}'
        }; 
     
        const result = await lambda.signUpHandler(event);
        const expectedResult = { 
            statusCode: 200,
            headers: {"Access-Control-Allow-Origin": allowOrigin},
            body: JSON.stringify({"success": true})
        }; 

        expect(result).toEqual(expectedResult); 
    }); 
}); 

When I run the test, I get this error:

Cannot spyOn on a primitive value; undefined given

      20 |         putSpy = jest.spyOn(dynamodb.DocumentClient.prototype, 'put'); 
    > 21 |         publishSpy = jest.spyOn(sns.prototype, 'publish')
         |                           ^
      22 |     }); 

Am I approaching this wrong? Any help would be greatly appreciated.

0 Answers
Related