How to enter transaction callback in typeorm?

Viewed 770

I'm kind of new in unit testing and trying to make some test with typeorm.

The code I've is this:

    public executeTransaction(querys: IQueryTransaction[]) {
        return getManager().transaction(async transactionalManager => {
            for (const query of querys) {
                await transactionalManager.query(query[0], query[1]);
            }
        });
    }

I need to enter the transaction callBack but can't figured out how to do it. I tried to mock getManager and transaction playing with it, but with no results.

I'm using jest, typeorm and nest.

Someone knows how to do this?.

EDIT: Connecting to the database is not an option

2 Answers

I think you should try something like this...

return await getManager().transaction(async transactionalManager => {
  for (const query of querys) {
    await transactionalManager.query(query[0], query[1]);
  }
});

OR

import {getManager} from "typeorm";

await getManager().transaction(async transactionalManager => {
    await transactionalManager.save(users);
    await transactionalManager.save(photos);
});

OR

@Controller("/user")
export class UserController {
    constructor(
        private userService: UserService,
    ) {}

    @Post("/")
    @Transaction()
    async createNewUser(@Body() body: UserDTO) {        
        return await this.userService.createNewUser(body);
    }
}

you can use Istambul to simplify your life.

/* istanbul ignore next */
Related