【问题标题】:Nest.js: initialization of property from controller's superclassNest.js:从控制器的超类初始化属性
【发布时间】:2020-01-24 10:18:47
【问题描述】:

我有一个关于 Nest.js 框架中的单元测试控制器的问题。问题是在创建测试模块时,控制器类中没有初始化超类的属性。

这是我正在谈论的示例代码:

export class MyController extends SomeOtherController {

    // Inherited from SomeOtherController
    async initSomeObject() {
        this.someObject = await initializeThisSomehow();
    }

    async controllerMethod(args: string) {
        // Do something
    }

}

export abstract class SomeOtherController implements OnModuleInit {

    protected someObject: SomeObject;

    async onModuleInit() {
        await this.initSomeObject();
    }

    abstract async initSomeObject(): Promise<void>;
}

这就是我创建测试的方式

describe('MyController', () => {
  let module: TestingModule;
  let controller: MyController;
  let service: MyService;

  beforeEach(async () => {
    module = await Test.createTestingModule({
      imports: [],
      controllers: [MyController],
      providers: [
        MyService,
        {
          provide: MyService,
          useFactory: () => ({
            controllerMethod: jest.fn(() => Promise.resolve()),
          }),
        },
      ],
    }).compile();

    controller = module.get(MyController);
    service = module.get(MyService);
  });

  describe('controller method', () => {
    it('should do something', async () => {
      jest.spyOn(service, 'controllerMethod').mockImplementation(async _ => mockResult);
      expect(await controller.controllerMethod(mockArgs)).toBe(mockResult);
    });
  });
});

现在,如果我要在开发模式下运行应用程序,someObject 属性将被初始化,并且代码可以正常工作。但是在运行测试时,似乎测试模块没有初始化它(所以它是未定义的)。

非常感谢任何形式的帮助。

【问题讨论】:

  • initStuff() (SomeOtherController) 在哪里调用?
  • 我的代码缺少关键细节:initStuff() 方法实际上被称为onModuleInit(),它来自OnModuleInit 接口,它是@nestjs/common 的一部分。我很抱歉犯了一个不小心的错误。问题已更新。

标签: javascript typescript testing jestjs nestjs


【解决方案1】:

在您的测试之前,您需要运行以下命令

await module.init(); // this is where onModuleInit is called

也最好关闭应用

afterEach(async () => await module.close());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-17
    • 2017-01-27
    • 1970-01-01
    • 2013-09-30
    • 2011-11-13
    • 1970-01-01
    • 2020-05-31
    • 2021-11-21
    相关资源
    最近更新 更多