0

I am a bit new to testing and I have been stuck on this issue for quite some time. So I am trying to test a s3.upload() function to see if it called, not to see if it actually uploads the object. The only constraint is that I cannot use any npm packages to mock out the functionality of the s3 bucket.

I was trying to follow this tutorial (How to mock a function inside another function (which I am testing) using sinon?) that uses sinon as a stub, but instead use jest instead. Any help or guidance with issue is appreciated.

// function.js
const uploadToS3 = (params) => {
    const response = s3.upload(params).promise();
    return response;
}

// functions.test.js
describe("Lambda Handler Function", () => {
    test('To test to see if the uploadToS3 function was called', () => {
        const sampleParam = {
            Bucket:  'BucketName',
            Key: 'BucketKey.zip',
            Body: 'SGVsbG8sIFdvcmxk'
        }
        expect(uploadToS3(sampleParam).response).toBeCalled()
    })
})  
0

1 Answer 1

0

You can use jest.mock(moduleName, factory, options) to mock aws-sdk. E.g.

function.js:

import AWS from 'aws-sdk';

const s3 = new AWS.S3();
const uploadToS3 = async (params) => {
  const response = await s3.upload(params).promise();
  return response;
};

export { uploadToS3 };

function.test.js:

import { uploadToS3 } from './function';
import AWSMock from 'aws-sdk';

jest.mock('aws-sdk', () => {
  const mS3 = { upload: jest.fn().mockReturnThis(), promise: jest.fn() };
  return { S3: jest.fn(() => mS3) };
});

describe('60970919', () => {
  it('should pass', async () => {
    const mS3 = new AWSMock.S3();
    const mResponse = { Bucket: 'xxx' };
    mS3.upload({}).promise.mockResolvedValueOnce(mResponse);
    const actual = await uploadToS3({});
    expect(actual).toEqual(mResponse);
    expect(mS3.upload).toBeCalledWith({});
    expect(mS3.upload().promise).toBeCalled();
  });
});

unit test results with 100% coverage:

 PASS  stackoverflow/60970919/function.test.js (13.818s)
  60970919
    ✓ should pass (9ms)

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

source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60970919

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.