【问题标题】:How to test a module in NestJs如何在 NestJs 中测试模块
【发布时间】:2018-02-25 19:57:15
【问题描述】:

我正在为一个项目添加测试并提高覆盖率。我想知道如何在 NestJs 中测试模块定义(mymodule.module.ts 文件)。 特别是,我正在测试一个导入其他模块的主模块,其中一个模块启动数据库连接,这意味着我需要在另一个模块上模拟服务,以避免真正的数据库连接。 此刻我有这样的事情:

beforeEach(async () => {
    const instance: express.Application = express();

    module = await NestFactory.create(MyModule, instance);
});
describe('module bootstrap', () => {
    it('should initialize entities successfully', async () => {
        controller = module.get(MyController);
        ...

        expect(controller instanceof MyController).toBeTruthy();
    });
});

这可行,但我相信这可以得到改进:)

理想的情况是 Test.createTestingModule 提供的 overrideComponent 方法。

P.S:我使用的是 4.5.2 版本

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    您现在可以通过构建它来测试您的模块(至少代码覆盖率):

    describe('MyController', () => {
       let myController: MyController;
    
       beforeEach(async () => {
          const module = await Test.createTestingModule({
             imports: [MyModule],
          }).compile();
    
          myController= module.get<MyController>(MyController);
       });
    
       it('should the correct value', () => {
         expect(myController.<...>).toEqual(<...>);
       });
    });
    

    【讨论】:

      【解决方案2】:

      我们通常不直接测试.module.ts 文件。


      我们在e2e 测试中这样做。

      但我想知道why one should test the the module ! 并且您正在尝试测试模块是否可以初始化它的组件,它应该。

      但我建议您在 e2e 测试中执行此操作。 在我看来,在单元测试中你应该专注于测试服务或其他组件的行为而不是模块。

      【讨论】:

      • 是的,我正在尝试测试一个模块是否可以成功初始化其所有依赖项。提高覆盖率将是附带的好处。像 medium.com/spektrakel-blog/… 这样的东西,但在 NestJs 版本中。
      • 另一个原因是在代码覆盖率报告上显示覆盖率,如果我们不测试它是红色的
      【解决方案3】:

      根据@laurent-thiebault 的回答改进了我的测试:

      import { Test } from '@nestjs/testing';
      import { ThingsModule } from './things.module';
      import { ThingsResolver } from './things.resolver';
      import { ThingsService } from './things.service';
      
      describe('ThingsModule', () => {
        it('should compile the module', async () => {
          const module = await Test.createTestingModule({
            imports: [ThingsModule],
          }).compile();
      
          expect(module).toBeDefined();
          expect(module.get(ThingsResolver)).toBeInstanceOf(ThingsResolver);
          expect(module.get(ThingsService)).toBeInstanceOf(ThingsService);
        });
      });
      

      【讨论】:

        猜你喜欢
        • 2023-03-24
        • 2021-07-15
        • 2019-08-06
        • 2020-06-22
        • 1970-01-01
        • 2022-01-26
        • 2022-06-12
        • 1970-01-01
        • 2021-05-30
        相关资源
        最近更新 更多