'Javascript nodeJs Postgres PG unit test using sinon

I'm using PG library to connect to Postgres DB.

Now, I want to write unit tests for database access and I don't know how I can do that. Actually, I need some mock Postgres server or something to mock Postgres.

I'm using Mocha/Sinon for testing

below is one of my classes to access database

import { Pool } from 'pg'
import Logger from './logger.js'
const logger = new Logger()

//const testCase = process.env.TEST_CASE.replace(/'/g, '')
const pool = new Pool({
  user: process.env.AURORA_USER,
  host: process.env.AURORA_HOST,
  database: process.env.AURORA_DB,
  password: process.env.AURORA_PASSWORD
})

pool.on('error', (err, client) => {
  logger.debug('Unexpected error on idle client', err)
  process.exit(-1)
})

export function writeLimits (runType, pipelineId, limitsData) {
  if (runType === 'before') {
    const text = `
      INSERT INTO "public"."data"(
        application,
        environment
      )
      VALUES($1, $2)
      RETURNING *;
    `
    const values = [
      process.env.PROJECT_NAME,
      process.env.ENVIRONMENT,
      process.env.TEST_RUN_CMD,
    ];

    (async () => {
      const client = await pool.connect()
      try {
        const res = await client.query(text, values)
        logger.info(`Step 1: Update "data" Table': ${JSON.stringify(res.rows[0])}`)
      } finally {
        // Make sure to release the client before any error handling,
        // just in case the error handling itself throws an error.
        client.release()
      }
    })().catch(err => logger.error(err.stack))
  } else if (runType === 'after') {
    (async () => {
      const client = await pool.connect()
      try {
        writeLimitsData(limitsData, client, 'post')
        logger.info('Step 3: Update Post Limits To The "limit" Table')
      } finally {
        // Make sure to release the client before any error handling,
        // just in case the error handling itself throws an error.
        client.release()
      }
    })().catch(err => logger.error(err.stack))
  }
}

Many thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source