本文介绍了如何模拟typeORM的getCustomRepository的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对在其构造函数中的getCustomRepository类进行单元测试,但我只是想不出一种简单的方法来模拟它.这是我的班级代码

I want to unit-test a class which getCustomRepository in it's constructor but I just can't figure an easy way to mock it. Here is my class code

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,这样可以减少尝试连接数据库所浪费的时间.

Note: Mocking repository methods works well but I really want to mock getCustomRepository so as It may reduce time which is wasted trying to connect to database.

这是typeORM中的getCustomRepository的样子

This is how getCustomRepository in typeORM looks like

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

UserRepository.ts

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;
}

所以问题是我该如何嘲笑它?任何帮助将不胜感激.

So question is how do I mock it? Any help will be much appreciated.

推荐答案

您可以使用 jest.mock(模块名称,工厂,选项)来模拟typeorm模块,getCustomRepository函数及其返回值.

You can use jest.mock(moduleName, factory, options) to mock typeorm module, getCustomRepository function and its returned value.

例如

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);
  });
});

具有覆盖率报告的单元测试结果:

unit test results with coverage report:

 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

这篇关于如何模拟typeORM的getCustomRepository的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 14:23