Last active
April 18, 2021 11:24
-
-
Save piyushchauhan2011/1160ea6783902a475064f78bbc539bff to your computer and use it in GitHub Desktop.
Run in Transaction test helper - TypeORM
This file contains hidden or 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
export function createRunInTransactionHelper<T extends BaseEntity>( | |
entity: EntityTarget<T>, | |
initFn: (tManager: EntityManager, repo: Repository<T>) => Promise<void>, | |
) { | |
return (fn: (repo: Repository<T>) => Promise<void>) => { | |
return getConnection().manager.transaction(async (tManager) => { | |
const repo = tManager.getRepository<T>(entity); | |
await initFn(tManager, repo); | |
await fn(repo); | |
tManager.queryRunner?.rollbackTransaction(); | |
}); | |
}; | |
} | |
// Example for using above | |
const runInTransaction = createRunInTransactionHelper<Admin>( | |
Admin, | |
async (tManager, adminRepo) => { | |
await adminRepo.save(adminRepo.create(mockAdmins)); | |
}, | |
); | |
// Example inside `test('')` function of jest | |
await runInTransaction(async (adminRepo) => { | |
const admins = await adminRepo.find(); | |
expect(admins.length).toBeGreaterThanOrEqual(mockAdmins.length); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment