Zach G
Zach G

Reputation: 645

How do you test Postgres with Node.js / Jest without mocking the pg import

I have 2 SQL queries I want to test, an INSERT and a SELECT. I want to run a test that calls the insert, and then calls the select, which should return the data from the insert.

I found a stackoverflow post about mocking postgres, but I want to actually run a test instance of postgres instead of mocking the actual queries.

Upvotes: 3

Views: 6841

Answers (1)

madflow
madflow

Reputation: 8500

An integration test with postgres could look like this:

const { Pool } = require('pg');

describe('testing postgres', () => {

    let pgPool;

    beforeAll(() => {
        pgPool = new Pool({
            connectionString: process.env.TEST_DATABASE_URL
        });
    });

    afterAll(async () => {
        await pgPool.end();
    });

    it('should test', async () => {
        const client = await pgPool.connect();
        try {
            await client.query('BEGIN');

            const { rows } = await client.query('SELECT 1 AS "result"');
            expect(rows[0]["result"]).toBe(1);

            await client.query('ROLLBACK');
        } catch(err) {
          throw err;
        } finally {
            client.release();
        }

    })

});

You would call this test with:

TEST_DATABASE_URL=postgresql://sth:sth@someserver/testdb jest

Testing an insert and select can be done by using RETURNING *.

     const { rows } = await client.query('INSERT INTO ... RETURNING *');

Using BEGIN and ROLLBACK is necessary - so you do not alter the database and have side effects for the next test to come.

Upvotes: 5

Related Questions