Open ffxsam opened 5 years ago
@ffxsam Did you ever solve this? I'm running into the same issue, though with the S3.upload
method (though I assume that doesn't make really any difference).
Jest 24.1.0, AWS-SDK 2.397.0.
I actually just sorted this out - you need to create your s3
object INSIDE the function you want to mock. So move
this.s3 = new AWS.S3({ apiVersion: API_VERSION });
from constructor()
to getMetadata()
and hopefully that should allow mocking to work. It was what finally worked for me.
I think the mocking of the service and calling of the mocked function should happen in same function according to the docs. Moving the code as suggested by @DanHulton would work, but I don't think it's wise to touch the Unit under test to make tests pass.
Here is how I would do 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', () => {
const makeS3Obj = () => {
AWS.mock('S3', 'headObject', (params, callback) => {
console.log('it works');
});
return new S3Object({
bucket: 'test-bucket',
key: 'some-folder/some-file.wav',
});
}
afterEach(() => {
AWS.restore();
});
it('gets metadata', async () => {
const s3Obj = makeS3Obj()
const metadata = await s3obj.getMetadata();
expect(metadata).toEqual({ userid: MOCK_USER_ID });
})
Another general comment, not releated to this code would be to use some sort of dependency injection so that you are in control of the dependencies passed.
I'm having a lot of trouble getting this to work. The actual
S3.headObject
is getting called, despite me mocking it.My "gets metadata" test is calling the real
S3.headObject
instead of the mocked version, for some reason. Here's thegetMetadata
method in myS3Object
class along with the constructor: