aws-sdk-js ReferenceError: You are trying to `import` a file after the Jest environment has been torn down

aws-sdk-js ReferenceError: You are trying to `import` a file after the Jest environment has been torn down

我需要测试是否返回了预签名的 url 存储桶 Amazon S3。

The Jest 在 运行 yarn test:

时显示以下消息
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      at Object.userAgent (node_modules/aws-sdk/lib/util.js:34:43)
      at HttpRequest.setUserAgent (node_modules/aws-sdk/lib/http.js:111:78)
      at new HttpRequest (node_modules/aws-sdk/lib/http.js:104:10)
      at MetadataService.request (node_modules/aws-sdk/lib/metadata_service.js:93:23)
      at MetadataService.fetchMetadataToken (node_modules/aws-sdk/lib/metadata_service.js:116:10)

这就是测试:

index.spec.js

const AWS = require('aws-sdk');

const bucketName = 'bucket';
const key = 'image.png';

describe('Test', () => {
  it('should be able return pre signed url', () => {
    const s3SigV4Client = new AWS.S3({
      signatureVersion: 'v4',
    });
    
    const s3PreSignedUrl = s3SigV4Client.getSignedUrl('getObject', {
      Bucket: bucketName,
      Key: key,
      Expires: 60,
    });

    expect(s3PreSignedUrl);
  });
});

package.json

{
  "name": "test_aws_sdk",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "test": "jest"
  },
  "dependencies": {
    "aws-sdk": "^2.807.0"
  },
  "devDependencies": {
    "jest": "^26.6.3"
  }
}

Node.js 和安装的 Yarn 版本:

$ node -v
v10.19.0
$ yarn -v
1.22.4

我做错了什么。

你能帮帮我吗?

导入后,在您的测试文件中添加jest.useFakeTimers()

示例:

const AWS = require('aws-sdk');

jest.useFakeTimers()

const bucketName = 'bucket';
const key = 'image.png';

describe('Test', () => {
  it('should be able return pre signed url', async () => {
    const s3SigV4Client = new AWS.S3({
      signatureVersion: 'v4',
    });
    
    const s3PreSignedUrl = s3SigV4Client.getSignedUrl('getObject', {
      Bucket: bucketName,
      Key: key,
      Expires: 60,
    });

    expect(s3PreSignedUrl);
  });
});