相关疑难解决方法(0)

如何模拟 typeORM 的 getCustomRepository

我想对一个在其构造函数中使用 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

这是测试

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(); …
Run Code Online (Sandbox Code Playgroud)

unit-testing node.js typescript jestjs typeorm

4
推荐指数
1
解决办法
1万
查看次数

标签 统计

jestjs ×1

node.js ×1

typeorm ×1

typescript ×1

unit-testing ×1