[英]Jest mock Knex transaction
I have the following lambda handler to unit test.我有以下 lambda 处理程序进行单元测试。 It uses a library @org/aws-connection
which has a function mysql.getIamConnection
which simply returns a knex connection.它使用一个库@org/aws-connection
,它有一个function mysql.getIamConnection
,它只返回一个knex连接。
Edit: I have added the mysql.getIamConnection
function to the bottom of the post编辑:我已将mysql.getIamConnection
function 添加到帖子底部
Edit: If possible, I'd like to do the testing with only Jest.编辑:如果可能的话,我想只用 Jest 进行测试。 That is unless it becomes to complicated那是除非它变得复杂
index.js 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
}
I have written some unit tests and I'm able to mock the connection.transaction
function but I'm having trouble with the trx.select.insert.then.catch functions.我已经编写了一些单元测试,并且能够模拟connection.transaction
function 但我遇到了 trx.select.insert.then.catch 函数的问题。 H H
Here is my testing file index.test.js这是我的测试文件 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)
});
});
This test works partially but it does not cover the trx
portion at all.此测试部分有效,但根本不涵盖trx
部分。 These lines are uncovered这些线是暴露的
await trx
.table('my_table')
.insert(records)
.then(() =>
console.log(`Records inserted into table ${table}`))
.catch((err) => {
console.log(err)
throw err
})
How can set up my mock @org/aws-connection
so that it covers the trx functions as well?如何设置我的模拟@org/aws-connection
以便它也涵盖 trx 功能?
Edit: mysql.getIamConnection编辑: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
}
Solution解决方案
@qaismakani's answer worked for me. @qaismakani 的回答对我有用。 I wrote it slightly differently but the callback was the key.我写的略有不同,但回调是关键。 For anyone interested here is my end solution对于任何对此感兴趣的人是我的最终解决方案
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()
}))
}
}))
Instead of mocking knex implementation, I've written knex-mock-client
which allows you to mimic real db with an easy API.我编写knex-mock-client
而不是 mocking knex 实现,它允许您使用简单的 API 模拟真实数据库。
Change your mock implementation with更改您的模拟实现
import { handler } from "../src";
import { getTracker } from "knex-mock-client";
const mocks = require("./mocks");
jest.mock("@org/aws-connection", () => {
const knex = require("knex");
const { MockClient } = require("knex-mock-client");
return {
mysql: {
getIamConnection: () => knex({ client: MockClient }),
},
};
});
describe("handler", () => {
test("test handler", async () => {
const tracker = getTracker();
tracker.on.insert("my_table").responseOnce([23]); // setup's a mock response when inserting into my_table
const response = await handler(mocks.eventSqs);
expect(response.statusCode).toEqual(200);
});
});
Okay, let's see.好吧,让我们看看。 Updating your mock to look like this might do the trick:更新你的模拟看起来像这样可能会奏效:
const {mysql} = require('@org/aws-connection');
jest.mock('@org/aws-connectionm, () => ({
mySql: {
getIamConnection: jest.fn()
}
}));
const mockTrx = {
table: jest.fn().mockReturnThis(),
insert: jest.fn().mockResolveValue() // resolve any data here
};
mysql.getIamConnection.mockReturnValue({
transaction: jest.fn((callback) => callback(mockTrx)),
});
Edit: Explanation编辑:解释
You need to mock transaction in a way that it calls your callback with a dummy trx.您需要以一种使用虚拟 trx 调用回调的方式模拟事务。 Now to get the dummy trx right, you need to make sure that all the functions inside dummy trx object return a reference back to it or a promise so that you can chain it appropriately.现在要正确获取虚拟 trx,您需要确保 dummy trx object 中的所有函数都返回对它的引用或 promise,以便您可以适当地链接它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.