aws-sdk-mock
aws-sdk-mock copied to clipboard
Unable to mock S3 using jest
I'm having a lot of trouble getting this to work. The actual S3.headObject
is getting called, despite me mocking it.
import AWS from 'aws-sdk-mock';
import S3 from 'aws-sdk/clients/s3';
import { Readable } from 'stream';
import { S3Object } from '../src/s3-object';
import { MOCK_USER_ID, MOCK_BUCKET, MOCK_KEY } from './constants';
describe('s3-object', () => {
let s3obj: S3Object;
beforeAll(() => {
AWS.mock('S3', 'headObject', (params, callback) => {
console.log('it works');
});
});
beforeEach(() => {
s3obj = new S3Object({
bucket: 'test-bucket',
key: 'some-folder/some-file.wav',
});
});
it('gets metadata', async () => {
const metadata = await s3obj.getMetadata();
expect(metadata).toEqual({ userid: MOCK_USER_ID });
});
My "gets metadata" test is calling the real S3.headObject
instead of the mocked version, for some reason. Here's the getMetadata
method in my S3Object
class along with the constructor:
constructor({ bucket, key }: S3ObjectProps) {
/**
* Instantiate S3 on the instance; future-proof to allow per-object config
* changes.
*/
this.s3 = new AWS.S3({ apiVersion: API_VERSION });
this.bucket = bucket;
this.key = key;
}
public async getMetadata(): Promise<AWS.S3.Metadata> {
const data = await this.s3
.headObject({
Bucket: this.bucket,
Key: this.key,
})
.promise();
return data.Metadata || {};
}