我在 API 网关中创建了一个新的 API 端点,映射了我的 AWS Lambda 函数,并想为处理对端点发出的请求的 JavaScript 方法编写测试用例。该方法使用 aws-sdk 节点模块创建到 AWS DynamoDB 的连接,以将传递的值保存到数据库并返回包含相关数据的
Promise
。我不希望 spec 触发对实际 DynamoDB 的调用或为其创建新条目。我尝试使用存根,但它仍然给我一个错误,指出测试用例失败。
Handler.js:
saveUser(userName, logger) {
const Item = {
id: uuid.v4(),
userName,
ttl: parseInt(Date.now() / 1000) + 900 // expire the name after 15 minutes from now
};
const params = {
TableName: "my-table-name"
};
logger.log(`Saving new user name to DynamoDB: ${JSON.stringify(params)}`);
return new Promise(function(resolve, reject) {
db.put(params, function(err, _) {
if (err) {
logger.exception(`Unable to connect to DynamoDB to create: ${err}`);
reject({
statusCode: 404,
err
});
} else {
logger.log(`Saved data to DynamoDB: ${JSON.stringify(Item)}`);
resolve({
statusCode: 201,
body: Item
});
}
});
});
}
Handler.spec.js:
import AWS from "aws-sdk";
const db = new AWS.DynamoDB.DocumentClient({
apiVersion: "2012-08-10"
});
describe("user-name-handler", function() {
const sandbox = sinon.createSandbox();
afterEach(() => sandbox.restore());
it("Test saveUser() method", async function(done) {
const {
saveUser
} = userHandler;
sandbox.stub(db, "put")
.returns(new Promise((resolve, _) => resolve({
statusCode: 200
})));
try {
const result = await saveToken("Sample User", {
log: () => {},
exception: () => {}
});
expect(result).to.be.equal({
data: "some data"
});
done();
} catch (err) {
console.log(err);
done();
}
});
});
错误:
Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
尝试将
function(done)
替换为 function()
并删除对 done()
; 的所有调用