javascript - 使用 Jest 测试时,类型错误 : AWS. DynamoDB.DocumentClient 不是构造函数

标签 javascript node.js unit-testing jestjs aws-sdk

我正在运行 Jest 测试来测试 dynamodb.js 文件和使用 dynamodb.js 文件的 create.js 文件。 create.js 模块是通用的,可以通过构造 param 对象并将其传递到其中来插入到任何表中。但是,我收到以下错误,我需要帮助。

TypeError: AWS.DynamoDB.DocumentClient is not a constructor

__mock__ folder

const getMock = jest.fn().mockImplementation(() => {
  return {
    promise() {
      return Promise.resolve({});
    }
  };
});

const putMock = jest.fn().mockImplementation(() => {
  return {
    promise() {
      return Promise.resolve({});
    }
  };
});

// eslint-disable-next-line func-names
function DynamoDB() {
  return {
    DocumentClient: jest.fn(() => ({
      get: getMock,
      put: putMock
    }))
  };
}

const AWS = { DynamoDB, getMock, putMock };
module.exports = AWS;

dynamodb.js

const AWS = require('aws-sdk');
const http = require('http');
const https = require('https');
const url = require('url');

module.exports = endpoint => {
  const { protocol } = url.parse(endpoint || '');

  const agentConfig = {
    keepAlive: true,
    keepAliveMsecs: 20000
  };

  const httpOptions =
    protocol === 'http:' ? { agent: new http.Agent(agentConfig) } : { agent: new https.Agent(agentConfig) };

  const db = new AWS.DynamoDB({
    endpoint,
    httpOptions
  });

  const docClient = new AWS.DynamoDB.DocumentClient({
    service: db
  });

  return {
    docClient,
    db
  };
};

dynamodb.spec.js

 
const AWS = require('aws-sdk');
const dynamodb = require('../../../src/dynamodb');

describe('dynamodb.js', () => {
  beforeEach(() => {
    // jest.resetModules();
  });

  test('calls generic-dynamodb-lib dynamodb', async () => {
    dynamodb('http://localhost:8001');

    expect(AWS.DynamoDB).toHaveBeenCalled();
    expect(AWS.DynamoDB.DocumentClient).toHaveBeenCalled();
  });
});

create.js

// Imports here

const create = async (log, docClient, table, tableRecord) => {
  try {
    await docClient.put({ TableName: table, Item: tableRecord }).promise();
  } catch (error) {
    log.error({ message: 'DynamoDB error', ...error });
    throw Error.internal();
  }

  return tableRecord;
};

module.exports = create;

我还尝试用 doMock block 替换 mock 中的手动模拟,但仍然继续出现上述相同的错误。 一旦我克服了这个问题,考虑到 docClient.js 被传递到函数中,我如何测试 create.js ?非常感谢。

最佳答案

DocumentClient 应该是静态属性,但它被模拟为实例属性。

应该是:

const DynamoDB = jest.fn().mockReturnValue({});
DynamoDB.DocumentClient = jest.fn().mockReturnValue({
  get: getMock,
  put: putMock
});

关于javascript - 使用 Jest 测试时,类型错误 : AWS. DynamoDB.DocumentClient 不是构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62672707/

相关文章:

javascript - 特定类型的数组,以及可能的好处和浏览器支持

node.js - 哪个 nosql 数据库适合?

javascript - 存储在 MySQL 与 JavaScript 对象中

javascript - 使用 Jest 进行 React 组件测试

javascript - 我可以在 mustache.js 模板中调用全局函数吗?

javascript - 我如何使用 jQuery 计算其他 div 中选择的类中的 div 的数量

javascript - Firebase 云函数获取用户 UID

javascript - MongoDB - 列表中每个 ID 的最新项目

python - 如何在模拟对象中 stub 方法?

c# - 有哪些工具可用于测试多线程 .net 代码?