Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

472
Views
Using spyOn with Jest to mock an AWS SNS publish call

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.

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!