【问题标题】:Mock postgres database connection(Pool, PoolClient, pg) using jest in typescript在打字稿中使用 jest 模拟 postgres 数据库连接(Pool,PoolClient,pg)
【发布时间】:2021-12-16 13:13:57
【问题描述】:

我有一个从 Postgres 数据库中获取值的简单函数。我需要通过模拟数据库来测试该方法。我尝试了提供的各种方法,但都没有奏效。总会出现一些错误。我尝试了以下解决方案:

以下是我的文件。

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


    【解决方案1】:

    以下方法对我有用

    fetch.test.ts

    import { fetch } from "./fetch";
    import pool from "./db";
    
    describe("Test fetch of so calls from database", () => {
      afterAll(() => {
        jest.resetAllMocks();
      });
      it("Happy case", async () => {
        (pool as any).connect = jest.fn().mockReturnThis();
        (pool as any).query = jest.fn().mockReturnThis();
        (pool as any).release = jest.fn().mockReturnThis();
        (pool as any).query.mockResolvedValueOnce({
          rows: [
            {
              v2: "EHRBFK76TGSMD",
              v3: "355GG",
              v4: "355GG",
              v1: "Q923892GT",
            },
          ],
        });
        const result = await fetchSiteCalls("Y2K");
        expect(result).toEqual([
          {
            rCode: "EHRBFK76TGSMD",
            dVo: "355GG",
            aVo: "355GG",
            service: { code: "Q923892GT" },
          },
        ]);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-07
      • 2019-09-24
      • 2020-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      相关资源
      最近更新 更多