针对实际数据库测试NestJS服务 [英] Test NestJS Service against Actual Database

查看:143
本文介绍了针对实际数据库测试NestJS服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够针对实际数据库测试Nest服务.我知道大多数单元测试都应使用模拟对象,但有时针对数据库本身进行测试也很有意义.

I would like to be able to test my Nest service against an actual database. I understand that most unit tests should use a mock object, but it also, at times, makes sense to test against the database itself.

我在SO和GH问题中搜索了Nest,并开始逐步解决所有问题. :-)

I have searched through SO and the GH issues for Nest, and am starting to reach the transitive closure of all answers. :-)

我正在尝试从 https://github.com/nestjs /nest/issues/363#issuecomment-360105413 .以下是我的单元测试,该测试使用自定义提供程序将存储库传递给我的服务类.

I am trying to work from https://github.com/nestjs/nest/issues/363#issuecomment-360105413. Following is my Unit test, which uses a custom provider to pass the repository to my service class.

describe("DepartmentService", () => {
  const token = getRepositoryToken(Department);
  let service: DepartmentService;
  let repo: Repository<Department>;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        DepartmentService,
        {
          provide: token,
          useClass: Repository
        }
      ]
    }).compile();

    service = module.get<DepartmentService>(DepartmentService);
    repo = module.get(token);
  });

一切正常编译,TypeScript看起来很高兴.但是,当我尝试在我的 Repository实例上执行createsave时,底层的Repository似乎未定义.这是堆栈回溯:

Everything compiles properly, TypeScript seems happy. However, when I try to execute create or save on my Repository instance, the underlying Repository appears to be undefined. Here's the stack backtrace:

TypeError: Cannot read property 'create' of undefined

  at Repository.Object.<anonymous>.Repository.create (repository/Repository.ts:99:29)
  at DepartmentService.<anonymous> (relational/department/department.service.ts:46:53)
  at relational/department/department.service.ts:19:71
  at Object.<anonymous>.__awaiter (relational/department/department.service.ts:15:12)
  at DepartmentService.addDepartment (relational/department/department.service.ts:56:16)
  at Object.<anonymous> (relational/department/test/department.service.spec.ts:46:35)
  at relational/department/test/department.service.spec.ts:7:71

似乎没有初始化具有TypeORM Repository类的EntityManager实例;它是此回溯抱怨的undefined参考.

It appears that the EntityManager instance with the TypeORM Repository class is not being initialized; it is the undefined reference that this backtrace is complaining about.

如何使RepositoryEntityManager正确初始化?

谢谢, 汤姆.

推荐答案

要正确初始化typeorm,您应该只能够在测试中导入TypeOrmModule:

To initialize typeorm properly, you should just be able to import the TypeOrmModule in your test:

Test.createTestingModule({
  imports: [
   TypeOrmModule.forRoot({
        type: 'mysql',
        // ...
   }),
   TypeOrmModule.forFeature([Department])
  ]

这篇关于针对实际数据库测试NestJS服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆