Skip to content

Instantly share code, notes, and snippets.

@michan85
Last active April 8, 2024 03:38
Show Gist options
  • Select an option

  • Save michan85/a31cdd991def8b22ee4eb82f331ba191 to your computer and use it in GitHub Desktop.

Select an option

Save michan85/a31cdd991def8b22ee4eb82f331ba191 to your computer and use it in GitHub Desktop.
Automatic Transaction rollback for unit testing sequelize using jest
jest.mock("sequelize", () => {
const s = jest.requireActual("sequelize")
const cls = require('cls-hooked');
const namespace = cls.createNamespace('unit-test');
s.useCLS(namespace);
return s
})
const autoRollbackTransaction = async (fn) => {
const sequelize = await (await require("./db/index").getConnection()).sequelize
try {
await sequelize.transaction(async (t) => {
await fn(sequelize)
throw new Error("rollback")
})
} catch (e) {
if (e.message != 'rollback')
throw e
}
}
// use it
test("should fail when password is invalid", async () => {
await autoRollbackTransaction(async (sequelize) => {
const testUser = TestUsers[0]
await expect(
SUT.authenticateUser(testUser.username, "invalid password")
).rejects.toThrow('Wrong email or password')
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment