Created
December 19, 2019 09:25
-
-
Save telendt/3e48afbb7c0ed3feb525d03dda107226 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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({ ... }) | |
})); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example of "asynchronous wrapper" used to set up DB connection with fully isolated transaction for testing purposes.