javascript aws-sdk-js参考错误:您正试图在Jest环境已关闭后“导入"文件

wljmcqd8  于 2023-01-19  发布在  Java
关注(0)|答案(2)|浏览(113)

我需要测试是否有一个预先签署的网址桶亚马逊S3返回。
运行yarn test时,Jest显示以下消息:

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)

这就是考验:

    • 索引规范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);
  });
});
    • 包. 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

我做错了什么。🤔
你能帮帮我吗?

yqkkidmi

yqkkidmi1#

导入后,在测试文件中添加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);
  });
});
bxgwgixi

bxgwgixi2#

尝试模拟示例:

jest.mock('dynamoose', () => ({
    aws: new class {
      sdk = { config: { update: jest.fn((arg) => arg) } };
    },
    Schema: class { },
    Condition: class { },
    transaction: new class { },
    model: jest.fn(),
    logger: new class { },
    UNDEFINED: new class { },
    THIS: new class { },
    NULL: new class { },
  }));

相关问题