[英]How to prevent constructor call in Lambda function test?
我有以下课程:
class Connection {
constructor() {
Log.debug('Constructor called!');
// Connect to DB
}
}
module.exports = Connection;
此类在Lambda函数中使用:
const Connection = require('Connection');
const connection = new Connection();
module.exports.endpoint = (event, context, callback) => {
// This will allow us to freeze open connections to a database
context.callbackWaitsForEmptyEventLoop = false;
// CODE HERE
}
上面的代码一旦在本地或部署到AWS上,效果很好。
现在,我有一个可以模拟数据库调用的测试。 但是,由于构造函数的原因,有两个副作用:
这是我测试的开始(实际上是调用Connection()
)
const mochaPlugin = require('serverless-mocha-plugin');
const { expect } = mochaPlugin.chai;
const sinon = require('sinon');
const wrapped = mochaPlugin.getWrapper('functionName', '/path/lambda.js', 'endpoint');
// Actual code starts below...
我确实尝试使用对Connection
类的sinon
和stub构造函数调用没有任何运气,因为基本上行mochaPlugin.getWrapper...
创建了连接。
如何防止构造函数调用? 三种存根是一种好方法吗?
附加信息:我正在使用sls invoke test
运行sls invoke test
由于尚无答案...这将起作用:
IS_LOCAL = true
然后在Connection类中检查它是否已设置,并修改构造函数以跳过与DB的连接。
constructor() {
if (!process.env.IS_LOCAL) {
// Connect to DB
}
}
这样,就无需更改测试代码和实际的lambda函数! 连接类也可以在其他地方重用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.