函数内部或外部的s3接口初始化
s3 interface initialization inside or outside the function
我们目前有:
export function s3Call(action: string, params: any): Promise<any> {
const s3 = new AWS.S3();
return s3[action](params).promise();
}
我尝试将其更改为:
const s3 = new AWS.S3();
export function s3Call(action: string, params: any): Promise<any> {
return s3[action](params).promise();
}
但是,在运行单元测试的时候,出现如下错误:
failed to get the current sub/segment from the context new s3
单元测试本身非常简单:
describe("uploadImage tests", () => {
it("should return correct image url", async () => {
process.env.IMAGE_UPLOAD_BUCKET_NAME = 'TestBucket';
process.env.AWS_REGION = 'us-west-2';
const putObject = jest.fn().mockImplementation(() => Promise.resolve({}));
AWSMock.mock('S3', 'putObject', putObject);
const bucketUrl = https://${process.env.IMAGE_UPLOAD_BUCKET_NAME}.s3-${process.env.AWS_REGION}.amazonaws.com/;
const result = await uploadImage(imageData, bucketUrl);
expect(result).toContain(process.env.IMAGE_UPLOAD_BUCKET_NAME);
expect(result).toContain(process.env.AWS_REGION);
AWSMock.restore('S3');
});
});
s3接口如何初始化一次?以及为什么我们从函数中取出 s3 初始化时会看到一次这个错误?
我相信您正在使用 aws-sdk-mock 节点包来模拟您的 S3 服务。
文档中说,
The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked
原因是当您在测试中导入包含 s3Call
的文件时,s3 服务实例已经创建(这不是存根而是实际实现)。因此,当您调用该函数时,它会使用现有实例而不是您期望的存根。
我们目前有:
export function s3Call(action: string, params: any): Promise<any> {
const s3 = new AWS.S3();
return s3[action](params).promise();
}
我尝试将其更改为:
const s3 = new AWS.S3();
export function s3Call(action: string, params: any): Promise<any> {
return s3[action](params).promise();
}
但是,在运行单元测试的时候,出现如下错误:
failed to get the current sub/segment from the context new s3
单元测试本身非常简单:
describe("uploadImage tests", () => {
it("should return correct image url", async () => {
process.env.IMAGE_UPLOAD_BUCKET_NAME = 'TestBucket';
process.env.AWS_REGION = 'us-west-2';
const putObject = jest.fn().mockImplementation(() => Promise.resolve({}));
AWSMock.mock('S3', 'putObject', putObject);
const bucketUrl = https://${process.env.IMAGE_UPLOAD_BUCKET_NAME}.s3-${process.env.AWS_REGION}.amazonaws.com/;
const result = await uploadImage(imageData, bucketUrl);
expect(result).toContain(process.env.IMAGE_UPLOAD_BUCKET_NAME);
expect(result).toContain(process.env.AWS_REGION);
AWSMock.restore('S3');
});
});
s3接口如何初始化一次?以及为什么我们从函数中取出 s3 初始化时会看到一次这个错误?
我相信您正在使用 aws-sdk-mock 节点包来模拟您的 S3 服务。
文档中说,
The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked
原因是当您在测试中导入包含 s3Call
的文件时,s3 服务实例已经创建(这不是存根而是实际实现)。因此,当您调用该函数时,它会使用现有实例而不是您期望的存根。