Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript TypeError:AWS.DynamoDB.DocumentClient在使用Jest进行测试时不是构造函数_Javascript_Node.js_Unit Testing_Jestjs_Aws Sdk - Fatal编程技术网

Javascript TypeError:AWS.DynamoDB.DocumentClient在使用Jest进行测试时不是构造函数

Javascript TypeError:AWS.DynamoDB.DocumentClient在使用Jest进行测试时不是构造函数,javascript,node.js,unit-testing,jestjs,aws-sdk,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 模拟文件夹 dynamodb.js dynamodb.spec.js create.js 我还尝试用doMock块替换mock中的手

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

TypeError: AWS.DynamoDB.DocumentClient is not a constructor
模拟文件夹

dynamodb.js

dynamodb.spec.js

create.js

我还尝试用doMock块替换mock中的手动mock,但仍然得到上面相同的错误。
一旦我解决了这个问题,考虑到docClient.js被传递到函数中,我如何测试create.js?非常感谢。

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

应该是:

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

非常感谢您的回复。 在这里看到回应之前,我已经找到了解决问题的方法

我最终不需要在
\uuuumock\uuuuu
目录中放置任何模拟

请参阅我提出的测试:

create.spec.js

dynamodb.spec.js


我刚刚看到你的评论。我已经能够使用下面的方法来实现它:``const fakePut=jest.fn().mockImplementation(()=>{return{promise(){return promise.resolve({});}};});const FakeDocumentClient=jest.fn(()=>({put:fakePut}));AWS.DynamoDB.DocumentClient=FakeDocumentClient```然而,我会尝试你的方法,让你知道它是否也适合我。
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
  };
};

 
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();
  });
});

// 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;

const DynamoDB = jest.fn().mockReturnValue({});
DynamoDB.DocumentClient = jest.fn().mockReturnValue({
  get: getMock,
  put: putMock
});
const AWS = require('aws-sdk');

const dynamodb = require('../../../src/dynamodb');

const create = require('../../../src/create');

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

  test('calls DocumentClient put with a successful outcome', async () => {
    const log = { error: jest.fn() };

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

    AWS.DynamoDB.DocumentClient = jest.fn(() => ({
      put: fakePut
    }));

    const document = {
      brands: ['visa', 'mc', 'amex', 'maestro', 'diners', 'discover', 'jcb']
    };

    const { docClient } = dynamodb('https://localhost:8001');
    await create(log, docClient, 'a-table-name', {
      countryCode: 'US',
      merchantAccount: 'MerchantAccountUS',
      expireAt: 1593814944,
      document
    });

    expect(create).toEqual(expect.any(Function));
    expect(fakePut).toHaveBeenCalled();
    expect(fakePut).toHaveBeenCalledWith({
      TableName: 'a-table-name',
      Item: {
        countryCode: 'US',
        merchantAccount: 'MerchantAccountUS',
        expireAt: 1593814944,
        document
      }
    });
  });

  test('calls DocumentClient put with unsuccessful outcome', async () => {
    const log = { error: jest.fn() };

    const fakePut = jest.fn().mockImplementation(() => {
      throw Error.internal();
    });

    AWS.DynamoDB.DocumentClient = jest.fn(() => ({
      put: fakePut
    }));

    const document = {
      brands: ['visa', 'mc', 'amex', 'maestro', 'diners', 'discover', 'jcb']
    };

    const { docClient } = dynamodb('https://localhost:8001');
    let thrownError;

    try {
      await create(log, docClient, 'a-table-name', {
        countryCode: 'US',
        merchantAccount: 'MerchantAccountUS',
        expireAt: 1593814944,
        document
      });
    } catch (e) {
      thrownError = e;
    }

    expect(create).toEqual(expect.any(Function));
    expect(fakePut).toHaveBeenCalled();
    expect(fakePut).toHaveBeenCalledWith({
      TableName: 'a-table-name',
      Item: {
        countryCode: 'US',
        merchantAccount: 'MerchantAccountUS',
        expireAt: 1593814944,
        document
      }
    });
    expect(thrownError).toEqual(Error.internal());
  });
});
const AWS = require('aws-sdk');
const http = require('http');
const https = require('https');
const url = require('url');
const dynamodb = require('../../../src/dynamodb');

const fakeFunction = jest.fn().mockImplementation(() => {});

const FakeDynamoDB = jest.fn(() => ({
  DocumentClient: fakeFunction
}));
AWS.DynamoDB = FakeDynamoDB;

const fakeGet = fakeFunction;
const fakePut = fakeFunction;

const FakeDocumentClient = jest.fn(() => ({
  get: fakeGet,
  put: fakePut
}));
AWS.DynamoDB.DocumentClient = FakeDocumentClient;

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

  test('calls DynamoDB and DocumentClient constructors with http protocol and with endpoint present', () => {
    const fakeParse = jest.fn().mockImplementation(() => 'http');
    url.parse = fakeParse;

    const fakeHttpAgent = jest.fn().mockImplementation(() => {});
    http.Agent = fakeHttpAgent;

    dynamodb('http://localhost:8001');

    expect(FakeDynamoDB).toHaveBeenCalled();
    expect(FakeDocumentClient).toHaveBeenCalled();
  });

  test('calls DynamoDB and DocumentClient constructors with https protocol and with endpoint present', () => {
    const fakeParse = jest.fn().mockImplementation(() => 'https');
    url.parse = fakeParse;

    const fakeHttpsAgent = jest.fn().mockImplementation(() => {});
    https.Agent = fakeHttpsAgent;

    dynamodb('https://localhost:8001');

    expect(FakeDynamoDB).toHaveBeenCalled();
    expect(FakeDocumentClient).toHaveBeenCalled();
  });
});