DynamoDB代码在Mocha测试用例中不起作用?

时间:2019-06-28 11:54:43

标签: amazon-dynamodb mocha aws-sdk aws-sdk-nodejs

背景: 我创建了一个Dynamo DB表并填充了它。我有一些代码可以读取名为readItem.js的文件中的项目,该文件在独立运行时可以运行,但在将其作为Mocha测试用例运行时不起作用。

有什么想法为什么代码不能在it()测试用例中正常运行?

对于独立版本,我可以这样运行应用程序:

node readItem.js

readItem.js:

var AWS = require("aws-sdk");

AWS.config.update({
  region: "us-west-2",
  endpoint: "http://localhost:8000"
});

var docClient = new AWS.DynamoDB.DocumentClient();
var table = "Movies";
var year = 2015;
var title = "The Big New Movie";
var params = {
    TableName: table,
    Key:{
        "year": year,
        "title": title
    }
};

docClient.get(params, function(err, data) {
    if (err) {
        console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
});

但是,当我在Mocha测试用例中运行它时,未调用docClient.get()调用上的回调函数,即:

docClient.get(params, function(err, data) { ...// Not being invoked });

这是我将代码结构化为测试用例的方式。我通过以下方式调用测试:

npm run test

在我的package.json中将“测试”定义为:

"scripts": {
"test": "./node_modules/.bin/mocha --recursive --reporter spec --ui bdd test/"
}

测试案例代码:

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

AWS.config.update({
  region: "us-west-2",
  endpoint: "http://localhost:8000"
});

var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
let table = "Movies";
let year = 2015;
let title = "The Big New Movie";
let params = {
    TableName: table,
    Key:{
        "year": year,
        "title": title
    }
};



describe('DynamoDB Tests', function() {

    it("Read Item", function() {

        try {
            docClient.get(params, function (err,data) {
                if (err) {
                    console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
                } else {
                    console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
                }               
            });
        } catch (err) {
            console.log("ERROR:"+ err);
        }

    });
});

1 个答案:

答案 0 :(得分:0)

我正在使用旧版本的摩卡咖啡: “ mocha”:“ ^ 3.5.3”

升级修复了它 “ mocha”:“ ^ 6.1.4”