开玩笑的嘲笑函数不被调用

时间:2020-07-17 09:29:50

标签: unit-testing mocking jestjs aws-sdk-js aws-sdk-mock

我在尝试在测试中调用模拟函数时遇到问题。

我的测试如下:

// test.js

const AWS = require('aws-sdk');
const AWSMock = require('aws-sdk-mock')
const { function1 } = require('../path/to/function');

describe('...', () => {
  test('... ', async () => {
    
    AWSMock.setSDKInstance(AWS);
    AWSMock.mock('DynamoDB.DocumentClient', 'scan', (params, callback) => {
      console.log('DynamoDB', 'scan', 'mock called');
      callback(null, { Count: mockedValue });
    });

    const response = await function1(params);

    // assertions 

    AWSMock.restore('DynamoDB.DocumentClient');
  });

});

我的函数文件如下:

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

const docClient = new AWS.DynamoDB.DocumentClient({
  region: 'eu-central-1',
  apiVersion: '2012-08-10',
});

const function1 = async (item) => {
  try {
    const params = { ... };
    const data = await docClient.put(params).promise();
    // more code
  } catch (error) {
    // error
  }
};

const function2 = async (item) => {
  try {
    const params = {...};
    const data = await docClient.update(params).promise();
    // more code
  } catch (error) {
    // error
  }
};

module.exports = {
  function1,
  function2,
};

以这种方式运行测试时,不会调用我的模拟函数。但是,如果我在每个函数内移动documentClient初始化,则会调用模拟函数。

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

const function1 = async (item) => {
  const docClient = new AWS.DynamoDB.DocumentClient({
   region: 'eu-central-1',
   apiVersion: '2012-08-10',
  });
 
  // more code
};

const function2 = async (item) => {
  const docClient = new AWS.DynamoDB.DocumentClient({
   region: 'eu-central-1',
   apiVersion: '2012-08-10',
  });
  
 // more code
};

是否可以在不将DocumentClient初始化移至每个函数的情况下使我的模拟工作正常?

0 个答案:

没有答案