Mocking of Managed Transaction block of sequlize

Viewed 598

Tech stack -> Typescript, Express Js, Sequlize typescript, Jest.

I am wring unit test cases for my project using jest. But I am stuck at how to mock managed transaction of sequlize.

await SequlizeConnection.sequelize.transaction(async (t) => {});

For initializing the database I have created a Class SequlizeConnection which has sequelize property.

export default class SequlizeConnection {
  public static sequelize: any; 

 public static createConnection() {
  this.sequelize = new Sequelize({
   //initializing the database here
  })
}

I tried to mock using below command but did not work.

SequlizeConnection.sequelize = jest.fn()
SequlizeConnection.sequelize.transaction = jest.fn();

If I used above code , then all the code in the tranaction block is not getting executed.

1 Answers

You can try to implement a mock function to sequelize.transaction and invoke a callback in the implementation. It looks something like below.

SequelizeConnection.sequelize.transaction = jest.fn().mockImplementation((transactionCallback) => {
    transactionCallback();
})
Related