【发布时间】:2021-12-16 13:13:57
【问题描述】:
我有一个从 Postgres 数据库中获取值的简单函数。我需要通过模拟数据库来测试该方法。我尝试了提供的各种方法,但都没有奏效。总会出现一些错误。我尝试了以下解决方案:
- How to Mock postgresql (pg) in node.js using jest
- How to mock pg Pool with Sinon
- Mock database Jest using ts-jest/utils
- How do you test Postgres with Node.js / Jest without mocking the pg importHow to test async await pg connection with jest?
- How to mock SQL Server connection pool using Jest?
- How to Mock postgresql (pg) in node.js using jest
以下是我的文件。
db.ts
import { Pool } from 'pg'
const pool = new Pool({
user: `${process.env.POSTGRES_USER}`,
database: `${process.env.POSTGRES_DB}`,
password: `${process.env.POSTGRES_PASSWORD}`,
port: `${process.env.POSTGRES_PORT}`,
host: `${process.env.POSTGRES_HOST}`,
})
export default pool;
fetch.ts
import pool from "./db";
import {SO} from "./s2l";
export async function fetch(code: string): Promise<SO[]>{
let socalls: SO[] =[]
const sql = 'Select sg.v1,sg.v2,sg.v3,sg.v4 from table1 sg where code = $1 and sg.r_code not in(\'ABC\', \'XYZ\', \'PQR\') order by sg.datetime asc'
const values = [code]
const client = await pool.connect()
await client.query(sql, values).then(res => {
const data = res.rows;
let so
data.forEach(row => {
so ={
service: {
code: row["v1"]
},
rCode: row["v2"],
dVo: row["v3"],
aVo: row["v4"],
};
socalls.push(so)
});
}).catch(e => console.error(e))
.then(() => client.release())
return Promise.all(socalls);
}
另外,我需要在查询中动态传递列表。
【问题讨论】:
标签: node.js typescript postgresql unit-testing jestjs