Как издеваться над getCustomRepository typeORM - PullRequest
0 голосов
/ 09 мая 2020

Я хочу провести модульное тестирование класса, который getCustomRepository в его конструкторе, но я просто не могу придумать простой способ имитировать его. Вот мой код класса

import {getCustomRepository} from 'typeorm';

export class Controller {
  private repository: UserRepository;

  constructor() {
    this.repository = getCustomRepository(UserRepository); //I want to mock this.
  }

  async init() {
    return this.repository.findUser(1);
  }
}

, а вот тесты

describe('User Tests', () => {
  it('should return user', async () => {
    //Fake user to be resolved.
    const user = new User();
    user.id = 2;

    //I want to mock  getCustomRepository(UserRepository); here
    //getCustomRepository = jest.fn().mockResolvedValue(UserRepository); HERE HOW???

    //Mocking find user
    UserRepository.prototype.findUser = jest.fn().mockResolvedValue(user);

    const controller = new Controller();
    const result = await controller.init();
    expect(result).toBeDefined();
  });
});

Примечание. Методы имитации репозитория работают хорошо, но я действительно хочу имитировать getCustomRepository, так как это может сократить время, которое тратится впустую. пытается подключиться к базе данных.

Так выглядит getCustomRepository в typeORM

export declare function getCustomRepository<T>(customRepository: ObjectType<T>, connectionName?: string): T;

UserRepository.ts

@EntityRepository(User)
export class UserRepository extends Repository<User> {
  public async findUser(id: number) {
    return 'real user';
  }
}

User.ts

@Entity('users')
export class User{
  @PrimaryGeneratedColumn()
  id: number;

  @Column({type: 'varchar', length: 100})
  name: string;
}

Итак, вопрос в том, как мне поиздеваться над этим? Любая помощь будет принята с благодарностью.

1 Ответ

1 голос
/ 11 мая 2020

Вы можете использовать jest.mock (moduleName, factory, options) для имитации typeorm модуля, getCustomRepository функции и ее возвращаемого значения.

Например,

controller.ts:

import { getCustomRepository } from 'typeorm';
import { UserRepository } from './userRepo';

export class Controller {
  private repository: UserRepository;

  constructor() {
    this.repository = getCustomRepository(UserRepository);
  }

  async init() {
    return this.repository.findUser(1);
  }
}

userRepo.ts:

export class UserRepository {
  public async findUser(id: number) {
    return 'real user';
  }
}

controller.test.ts:

import { Controller } from './controller';
import { getCustomRepository } from 'typeorm';
import { mocked } from 'ts-jest/utils';
import { UserRepository } from './userRepo';

jest.mock('typeorm', () => ({ getCustomRepository: jest.fn() }));

describe('61693597', () => {
  it('should pass', async () => {
    const userRepo = { findUser: jest.fn().mockResolvedValueOnce('fake user') };
    mocked(getCustomRepository).mockReturnValueOnce(userRepo);
    const controller = new Controller();
    const actual = await controller.init();
    expect(actual).toBe('fake user');
    expect(getCustomRepository).toBeCalledWith(UserRepository);
    expect(userRepo.findUser).toBeCalledWith(1);
  });
});

результаты модульного тестирования с отчетом о покрытии:

 PASS  stackoverflow/61693597/controller.test.ts (13.53s)
  61693597
    ✓ should pass (9ms)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |   92.31 |      100 |      80 |   90.91 |                   
 controller.ts |     100 |      100 |     100 |     100 |                   
 userRepo.ts   |      80 |      100 |      50 |      75 | 3                 
---------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        15.596s

исходный код: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61693597

...