【发布时间】:2021-08-10 08:54:15
【问题描述】:
我有以下 lambda 处理程序来进行单元测试。它使用一个库@org/aws-connection,它有一个函数mysql.getIamConnection,它只返回一个knex连接。
编辑:我在帖子底部添加了mysql.getIamConnection 函数
编辑:如果可能的话,我想只用 Jest 进行测试。那是除非它变得复杂
index.js
const {mysql} = require('@org/aws-connection');
exports.handler = async (event) => {
const connection = await mysql.getIamConnection()
let response = {
statusCode: 200,
body: {
message: 'Successful'
}
}
try {
for(const currentMessage of event.Records){
let records = JSON.parse(currentMessage.body);
await connection.transaction(async (trx) => {
await trx
.table('my_table')
.insert(records)
.then(() =>
console.log(`Records inserted into table ${table}`))
.catch((err) => {
console.log(err)
throw err
})
})
}
} catch (e) {
console.error('There was an error while processing', { errorMessage: e})
response = {
statusCode: 400,
body: e
}
} finally {
connection.destroy()
}
return response
}
我已经编写了一些单元测试,并且能够模拟 connection.transaction 函数,但我在使用 trx.select.insert.then.catch 函数时遇到了问题。 H
这是我的测试文件 index.test.js
import { handler } from '../src';
const mocks = require('./mocks');
jest.mock('@org/aws-connection', () => ({
mysql: {
getIamConnection: jest.fn(() => ({
transaction: jest.fn(() => ({
table: jest.fn().mockReturnThis(),
insert: jest.fn().mockReturnThis()
})),
table: jest.fn().mockReturnThis(),
insert: jest.fn().mockReturnThis(),
destroy: jest.fn().mockReturnThis()
}))
}
}))
describe('handler', () => {
test('test handler', async () =>{
const response = await handler(mocks.eventSqs)
expect(response.statusCode).toEqual(200)
});
});
此测试部分有效,但根本不涵盖trx 部分。这些线没有被发现
await trx
.table('my_table')
.insert(records)
.then(() =>
console.log(`Records inserted into table ${table}`))
.catch((err) => {
console.log(err)
throw err
})
如何设置我的模拟 @org/aws-connection 使其也涵盖 trx 功能?
编辑: mysql.getIamConnection
async function getIamConnection (secretId, dbname) {
const secret = await getSecret(secretId)
const token = await getToken(secret)
let knex
console.log(`Initialzing a connection to ${secret.proxyendpoint}:${secret.port}/${dbname} as ${secret.username}`)
knex = require('knex')(
{
client: 'mysql2',
connection: {
host: secret.proxyendpoint,
user: secret.username,
database: dbname,
port: secret.port,
ssl: 'Amazon RDS',
authPlugins: {
mysql_clear_password: () => () => Buffer.from(token + '\0')
},
connectionLimit: 1
}
}
)
return knex
}
解决方案
@qaismakani 的回答对我有用。我写的略有不同,但回调是关键。对于任何对此感兴趣的人,这是我的最终解决方案
const mockTrx = {
table: jest.fn().mockReturnThis(),
insert: jest.fn().mockResolvedValue()
}
jest.mock('@org/aws-connection', () => ({
mysql: {
getIamConnection: jest.fn(() => ({
transaction: jest.fn((callback) => callback(mockTrx)),
destroy: jest.fn().mockReturnThis()
}))
}
}))
【问题讨论】:
-
如果
connection.transaction被成功模拟,我看不出它如何在回调中返回一个真实的事务对象(trx)? -
你是对的,它并没有真正成功,因为它在回调中没有 trx。我想这就是这个问题的重点。但是,它确实模拟了 connection.transaction。
标签: node.js unit-testing aws-lambda jestjs knex.js