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.