nestjs - 如何在 Nestjs/TypeORM 应用程序中测试自定义 Repository

标签 nestjs typeorm

我正在尝试添加更多测试代码以提高示例代码的质量。
目前,我在测试时遇到问题 UserRepository ( 不是模拟 UserRepository ),我在自定义 UserRepository 中添加了一些自定义方法像这样。

@EntityRepository(UserEntity)
export class UserRepository extends Repository<UserEntity> {
  findByEmail(email: string): Promise<UserEntity> {
    return this.findOne({ email: email });
  }
}
所以我想验证findOne从父级 Repository 调用.
我尝试添加以下测试代码。
describe('UserRepository', () => {
  let local;
  let parentMock;

  beforeEach(() => {
    local = Object.getPrototypeOf(UserRepository);
    parentMock = {
      new: jest.fn(),
      construtor: jest.fn(),
      findOne: jest.fn(),
    };
    Object.setPrototypeOf(UserRepository, parentMock);
  });

  afterEach(() => {
    Object.setPrototypeOf(UserRepository, local);
  });

  it('should call findOne', async () => {
    const findByEmailSpy = jest.spyOn(parentMock, 'findOne');
    const users = new UserRepository();
    await users.findByEmail('test@example.com');
    expect(parentMock.mock.calls.length).toBe(1);
    expect(findByEmailSpy).toBeCalledWith({
      email: 'test@example.com',
    });
  });
});
运行测试时,它提示 new UserRepository() 没有构造函数() .
有没有办法解决这个问题,或者有更好的方法来编写这些测试代码?

最佳答案

为了正确测试用户存储库,findOne方法必须被模拟。

import { Test, TestingModule } from '@nestjs/testing';
import { Repository } from 'typeorm';
import { UserEntity } from './user.entity';
import { UserRepository } from './user.repository';

describe('UserRepository', () => {
  let userRepository: UserRepository;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [UserRepository],
    }).compile();

    userRepository = module.get<UserRepository>(UserRepository);
  });

  describe('findByEmail', () => {
    it('should return found user', async () => {
      const email = 'email';
      const user = {
        email,
      };
      const findOneSpy = jest
        .spyOn(userRepository, 'findOne')
        .mockResolvedValue(user as UserEntity);

      const foundUser = await userRepository.findByEmail(email);
      expect(foundUser).toEqual(user);
      expect(findOneSpy).toHaveBeenCalledWith(user);
    });
  });
});

关于nestjs - 如何在 Nestjs/TypeORM 应用程序中测试自定义 Repository,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67580233/

相关文章:

javascript - NestJs/Mongoose 同一模型的多个模式

mongoose - 使用 Mongoose 崩溃在 NestJS 中实例化新文档

node.js - 在全局(单例)服务中使用特定于请求的上下文

nestjs - 在 nestJs 多文件上传中找不到 diskStorage()

javascript - 将nestjs与哨兵集成

postgresql - TypeORM 中的 Postgres 枚举

database - 使用 typeORM 搜索早于日期的数据

typescript - 将 TypeORM 实体模型类与 NestJS-GraphQL 模式类型结合使用好吗?

typescript - TypeORM OneToMany 导致 "ReferenceError: Cannot access ' <Entity >' before initialization"

mysql - 具有别名的计算列未映射到 TypeORM 实体