首页 > 解决方案 > S3Client 不是 Jest 中的构造函数

问题描述

我正在尝试使用 Jest 测试基本的 S3 命令,但使用模拟后出现错误。不知道我错在哪里。

我正在查看实现和单元测试部分,但不明白我为什么要这样做。

https://docs.aws.amazon.com/code-samples/latest/catalog/javascriptv3-tests-s3-s3.test.js.html

aws-s3.js

const { S3Client,  HeadBucketCommand, CreateBucketCommand } = require("@aws-sdk/client-s3");
const { REGION } = require('../config');

// Create S3 service object
const s3 = new S3Client({ region: REGION });

const createS3Bucket = async ({ bucketName }) => {
  
  const bucket = await isBucketExists({ bucketName });//some other function in the same file

  if (!bucket) {
    try {
      const data = await s3.send(new CreateBucketCommand({ Bucket: bucketName }));
      console.log(`Bucket ${bucketName} created successfully`);      
      return data;
    } catch (err) {
      console.log(`Bucket ${bucketName} couldn't create`);      
      return null;
    }
  }
  
  return bucket;
};

s3.test.js

var faker = require('faker');

const mockCreateBucket = jest.fn();

jest.mock("@aws-sdk/client-s3", () => ({
    S3: function S3() {
        this.createBucket = mockCreateBucket;
    },
}));

const { createS3Bucket } = require("../utils/aws-s3");

test("has to mock S3#createBucket", async (done) => {
    const bucketName = faker.random.word();
    await createS3Bucket(bucketName);
    expect(mockCreateBucket).toHaveBeenCalledWith(bucketName);
    done();
});

错误

TypeError: S3Client is not a constructor

  3 |
  4 | // Create S3 service object
> 5 | const s3 = new S3Client({ region: REGION });
    |            ^
  6 |
  7 | const isBucketExists = async ({ bucketName }) => {
  8 |   try {

  at Object.<anonymous> (utils/aws-s3.js:5:12)
  at Object.<anonymous> (__test__/s3.test.js:11:28)

谢谢

标签: javascriptamazon-s3jestjs

解决方案


推荐阅读