connection.mock.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import { AbstractRepository, EntityManager, Repository } from 'typeorm';
  2. import { Type } from '../common/common-types';
  3. import { MockClass } from './testing-types';
  4. /**
  5. * A mock of the TypeORM Connection class for use in testing.
  6. */
  7. export class MockConnection {
  8. manager: MockEntityManager;
  9. private repositoryMap = new Map<Type<any>, any>();
  10. constructor() {
  11. this.manager = new MockEntityManager();
  12. this.manager.connection = this;
  13. }
  14. registerMockRepository<T extends Type<any>>(entity: T): MockRepository<T> {
  15. const repository = new MockRepository();
  16. this.repositoryMap.set(entity, repository);
  17. return repository;
  18. }
  19. getRepository<T extends Type<any>>(entity: T): MockRepository<T> {
  20. const repository = this.repositoryMap.get(entity);
  21. if (repository) {
  22. return repository;
  23. } else {
  24. throw new Error(`No mock repository registered for "${entity.name}". Use registerRepository() first.`);
  25. }
  26. }
  27. }
  28. export class MockRepository<T> implements MockClass<Repository<T>> {
  29. manager: any;
  30. metadata: any;
  31. queryRunner: any;
  32. target: any;
  33. createQueryBuilder = jest.fn();
  34. hasId = jest.fn();
  35. getId = jest.fn();
  36. create = jest.fn();
  37. merge = jest.fn();
  38. preload = jest.fn();
  39. save = jest.fn();
  40. remove = jest.fn();
  41. insert = jest.fn();
  42. update = jest.fn();
  43. delete = jest.fn();
  44. count = jest.fn();
  45. find = jest.fn();
  46. findAndCount = jest.fn();
  47. findByIds = jest.fn();
  48. findOne = jest.fn();
  49. findOneOrFail = jest.fn();
  50. query = jest.fn();
  51. clear = jest.fn();
  52. increment = jest.fn();
  53. decrement = jest.fn();
  54. }
  55. export class MockEntityManager implements MockClass<EntityManager> {
  56. connection: any = {};
  57. queryRunner: any = {};
  58. transaction = jest.fn();
  59. query = jest.fn();
  60. createQueryBuilder = jest.fn();
  61. hasId = jest.fn();
  62. getId = jest.fn();
  63. create = jest.fn();
  64. merge = jest.fn();
  65. preload = jest.fn();
  66. save = jest.fn();
  67. remove = jest.fn();
  68. insert = jest.fn();
  69. update = jest.fn();
  70. delete = jest.fn();
  71. count = jest.fn();
  72. find = jest.fn();
  73. findAndCount = jest.fn();
  74. findByIds = jest.fn();
  75. findOne = jest.fn();
  76. findOneOrFail = jest.fn();
  77. clear = jest.fn();
  78. increment = jest.fn();
  79. decrement = jest.fn();
  80. getRepository = jest.fn();
  81. getTreeRepository = jest.fn();
  82. getMongoRepository = jest.fn();
  83. getCustomRepository = jest.fn();
  84. release = jest.fn();
  85. }