使用 Jest 和 AWS-SDK-mock、模拟 DynamoDB 扫描进行单元测试



>跳入Jest和单元测试lambda函数。 我正在尝试在我的单元测试中模拟 aws dynamodb 文档客户端扫描。 不过,我正在从真实数据库获取实际扫描,因此我知道我的模拟某些内容不起作用。 这是我的.test.js:

var AWS = require('aws-sdk-mock');
const sinon = require('sinon');
let index = require('./index.js');

beforeEach(()=> {
AWS.mock('DynamoDB.DocumentClient', 'scan', function(params, callback) {
callback(null, {test: "value"});
})
});
afterEach(()=> {
AWS.restore();
});
it( 'test invocation', async() => {
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
const result = await index.handler({}, {}, (err, result) => {
expect(result).toEqual({test: "value"});
});
});

我的实际 lambda 函数代码如下所示:

'use strict';
var AWS = require("aws-sdk");
var DOC = require("dynamodb-doc");
AWS.config.update({region: "us-east-1"//,
});
var docClient = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: "table-name",
FilterExpression: "#PK = :cat_val",
ExpressionAttributeNames: {"#PK": "PK",},
ExpressionAttributeValues: { ":cat_val": "Value"}
};
exports.handler = (event, context, callback) => {
var response; 

docClient.scan(params, onScan);
function onScan(err, data) {
if (err) {
response = {
statusCode: 500,
body: "Unable to complete scan.  Error JSON: " + JSON.stringify(err,null,2)
}
} else {
data.Items.sort(compare);
response = {
statusCode: 200,
body: data.Items
}
}
callback(null, response);
console.log(response);
}
}

你们可以指出我的任何方向。 测试在相等比较时失败,因为它具有来自 Dynamo 扫描的实际响应。

谢谢 提姆

因此,问题出在您的函数中,在它被称为 AWS sdk 之前正在初始化,因此它总是会在处理程序执行之前创建该对象。

您需要模拟 AWS 库,以便将测试与您尝试检查的函数隔离开来

const DocumentClient = require("aws-sdk/clients/dynamodb");
const documentClient = new DocumentClient({ region: process.env.AWS_REGION }); // Set the AWS_REGION on your lambda
exports.handler = (event, context, callback) => {
var response; 
var params = {
TableName: "table-name",
FilterExpression: "#PK = :cat_val",
ExpressionAttributeNames: {"#PK": "PK",},
ExpressionAttributeValues: { ":cat_val": "Value"}
};
documentClient.scan(params, onScan);
function onScan(err, data) {
if (err) {
response = {
statusCode: 500,
body: "Unable to complete scan.  Error JSON: " + JSON.stringify(err,null,2)
}
} else {
data.Items.sort(compare);
response = {
statusCode: 200,
body: data.Items
}
}
callback(null, response);
console.log(response);
}
}

因此,您可以使用dynamoDB DocumentCient的手动模拟来进行测试

const index = require('./index.js');
const mockDynamoDbScan = jest.fn();
jest.mock('aws-sdk/clients/dynamodb', () => ({
DocumentClient: jest.fn().mockImplementation(() => ({
scan: mockDynamoDbScan
}))
}))
describe('executeGet', () => {
beforeEach(() => {
jest.resetAllMocks();
process.env.TABLE_NAME = 'SomeTable';
process.env.AWS_REGION = 'someRegion';
});
it('Returns an item', () => {
// Assemble - get the left and right of together
mockDynamoDbScan.mockReturnValue({ Items: [] });
// Action - execute functions
let errResult;
let functionResult;
index.handler({}, {}, (err, result) => {
errResult = err
functionResult = result
})
// Assert - just populated some potential cases you may want to use
expect(functionResult).toBeDefined();
expect(functionResult.statusCode).toBeDefined();
expect(functionResult.Items.length).toEqual(0);
}):
}));

由于在这里格式化它,我可能会有一些代码略有错误,但这应该为您提供所需的要点。如果这需要更新,请告诉我

最新更新