Skip to content Skip to sidebar Skip to footer

Using Jest.fn() To See If S3.upload Function Was Called...what Am I Doing Wrong?

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 uplo

Solution 1:

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

function.js:

importAWSfrom'aws-sdk';

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

export { uploadToS3 };

function.test.js:

import { uploadToS3 } from'./function';
importAWSMockfrom'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 = newAWSMock.S3();
    const mResponse = { Bucket: 'xxx' };
    mS3.upload({}).promise.mockResolvedValueOnce(mResponse);
    const actual = awaituploadToS3({});
    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

Post a Comment for "Using Jest.fn() To See If S3.upload Function Was Called...what Am I Doing Wrong?"