0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TypeORMのEntityManagerをJestでMock化する方法

Posted at

はじめに

色々調べたけど「これ!」というのが見つからなかったので備忘録として。

やりたいこと

にあるような

import {getManager} from "typeorm";

await getManager().transaction(async transactionalEntityManager => { 
   await transactionalEntityManager.save(students); 
});

という使い方をしている場合に、 transaction をモック化したい。

実際の実装

こんな感じ

beforeAll(() => {
  const mockGetManager = jest.spyOn(typeorm, "getManager");
  const entityManager = {} as EntityManager;

  mockGetManager.mockImplementation(() => {
    async function mockTransaction(func: any) {
      entityManager.save = function save(entity: any): Promise<any> {
        return Promise.resolve(true);
      };

      entityManager.update = function update(entity: any, update: any): Promise<any> {
        return Promise.resolve(true);
      };

      entityManager.findOne = function findOne(query: any): Promise<any> {
        return Promise.resolve(true);
      };

      entityManager.find = function find(query?: any): Promise<Array<any>> {
        return Promise.resolve([]);
      };

      entityManager.delete = function del(query: any): Promise<any> {
        return Promise.resolve(true);
      };

      return await Promise.resolve(func(entityManager));
    }

    entityManager.transaction = jest.fn().mockImplementation(mockTransaction);
    return entityManager;
  });
});

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?