Last active
April 8, 2024 03:38
-
-
Save michan85/a31cdd991def8b22ee4eb82f331ba191 to your computer and use it in GitHub Desktop.
Automatic Transaction rollback for unit testing sequelize using jest
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
| 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