如何防止在 Lambda 函数测试中调用构造函数?
How to prevent constructor call in Lambda function test?
我关注class:
class Connection {
constructor() {
Log.debug('Constructor called!');
// Connect to DB
}
}
module.exports = Connection;
这个class在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...
我确实尝试使用 sinon
和对 Connection
class 的存根构造函数调用,但没有成功,因为基本上 mochaPlugin.getWrapper...
行创建了连接。
如何防止构造函数调用?三个是一种干净整洁的存根方法吗?
其他信息:我 运行 我的测试 sls invoke test
因为还没有答案...这行得通:
- 添加环境变量:
IS_LOCAL = true
然后在 Connection class 中检查是否已设置并修改构造函数以跳过与 DB 的连接。
constructor() {
if (!process.env.IS_LOCAL) {
// Connect to DB
}
}
这样就不需要更改测试代码和实际的 lambda 函数了!其他地方的连接 class 也可以是 re-used。
我关注class:
class Connection {
constructor() {
Log.debug('Constructor called!');
// Connect to DB
}
}
module.exports = Connection;
这个class在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...
我确实尝试使用 sinon
和对 Connection
class 的存根构造函数调用,但没有成功,因为基本上 mochaPlugin.getWrapper...
行创建了连接。
如何防止构造函数调用?三个是一种干净整洁的存根方法吗?
其他信息:我 运行 我的测试 sls invoke test
因为还没有答案...这行得通:
- 添加环境变量:
IS_LOCAL = true
然后在 Connection class 中检查是否已设置并修改构造函数以跳过与 DB 的连接。
constructor() {
if (!process.env.IS_LOCAL) {
// Connect to DB
}
}
这样就不需要更改测试代码和实际的 lambda 函数了!其他地方的连接 class 也可以是 re-used。