我正在为使用aws-sdk列出s3存储桶中的所有文件的服务编写单元测试。 在函数内部,我实例化了S3类,并使用了从S3存储桶中获取文件的listObjectsV2,在测试中,我应该模拟该函数以返回虚拟数据。
问题是我找不到模拟实例化类以覆盖函数的方法,我不想在参数(依赖注入)中传递S3对象
aws.service:
const params: S3.ListObjectsV2Request = {
Bucket: bucket,
EncodingType: 'url',
StartAfter: documentsPath
};
return this.listAllFilesCore(params);
}
private listAllFilesCore(params: S3.ListObjectsV2Request): Promise<ObjectList> {
return new Promise<ObjectList>((resolve, reject) => {
let result: ObjectList = []; const s3bucket = new S3(this.config);
s3bucket.listObjectsV2(params, (err, data) => {
if (err) {
logger.error(err.message);
logger.error(err.stack);
reject(err);
} else {
result = result.concat(data.Contents);
if (data.IsTruncated) {
logger.debug('get further list...');
this.listAllFilesCore(Object.assign(params, { ContinuationToken: data.NextContinuationToken }))
.then(r => {
result = result.concat(r);
resolve(result);
});
} else {
logger.debug(`get S3 Success from ${params.StartAfter}`);
resolve(result);
}
}
});
});
}
let awsService: any;
beforeAll(() => {
jest.mock('aws-sdk/clients/s3');
awsService = require('./aws.service').awsService;
});
it('listAllFiles from S3', () => {
const S3 = require('aws-sdk/clients/s3');
S3.listObjectsV2 = jest.fn((param: any,
callback?: (err: any, data: any) => void) => {
callback(undefined, data2);
});
我收到TypeError:s3bucket.listObjectsV2不是函数
答案 0 :(得分:0)
您可以使用jest.mock(moduleName, factory?)
方法手动模拟导入的模块。这是文档:https://jestjs.io/docs/en/manual-mocks