Mocking aws-sdk S3#putObject instance method using jest
For the source code
//src.js
const S3 = require('aws-sdk/clients/s3');
const s3 = new S3();
const putFunction = () => {
s3.putObject(params, callback);
}
export default putFunction;
Following approach can be used to mock the putObject method of S3 client.
const mockedPutObject = jest.fn();
jest.mock('aws-sdk/clients/s3', () => {
return class S3 {
putObject(params, cb) {
mockedPutObject(params, cb);
}
}
});
it('has to mock S3#putObject', () => {
const putFunc = require('./src).default.putFunc;
putFunc();
expect(mockedPutObject).toHaveBeenCalledWith(params, callback);
})
You can use jest.fn().mockImplementation
// index.js
const AWS = require('aws-sdk')
const s3 = new AWS.S3()
s3.putObject({},()=> {
return 2;
});
// your test under test folder
let AWS = require('aws-sdk');
describe('test', () => {
let result;
beforeEach(()=>{
AWS.S3 = jest.fn().mockImplementation( ()=> {
return {
putObject (params, cb) {
result = cb();
}
};
});
require('../index');
});
test('call s3', () => {
expect(result).toBe(2);
});
});