Skip to content

Instantly share code, notes, and snippets.

@telendt
Created December 19, 2019 09:25
Show Gist options
  • Save telendt/3e48afbb7c0ed3feb525d03dda107226 to your computer and use it in GitHub Desktop.
Save telendt/3e48afbb7c0ed3feb525d03dda107226 to your computer and use it in GitHub Desktop.
const withDatabase = require('../utils');
describe('model.getUsers', () => {
it('returns all users', withDatabase([
{ _table: 'user', id: 1, name: 'User 1' },
{ _table: 'user', id: 1, name: 'User 1' },
], async (model) => {
expect(model.getUsers()).toMatchObject([...]);
}));
});
describe('model.createUser', () => {
it('create user', withDatabase([], async (model) => {
expect(model.createUser('test user')).toMatchObject({ ... })
}));
});
const { Client } = require('pg');
const { stripIndent } = require('common-tags');
const model = require('../src/model');
function withDatabase(fixtures, testFun) {
return async () => {
const db = new Client({ database: global.TEST_DATABASE_NAME });
await db.connect();
await db.query('BEGIN');
try {
for (const fixture of fixtures) {
const fields = Object.keys(fixture).filter((f) => f.charAt(0) !== '_');
await db.query(stripIndent`
INSERT INTO ${fixture._table} (${fields.join(', ')})
VALUES (${fields.map((_, i) => `$${i + 1}`)})
`, fields.map((f) => fixture[f]));
}
await testFun(new Model(db););
} finally {
await db.query('ROLLBACK');
await db.end();
}
};
}
module.exports = withDatabase;
@telendt
Copy link
Author

telendt commented Dec 19, 2019

example of "asynchronous wrapper" used to set up DB connection with fully isolated transaction for testing purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment