繁体   English   中英

Nest.js:从控制器的超类初始化属性

[英]Nest.js: initialization of property from controller's superclass

我对 Nest.js 框架中的单元测试控制器有疑问。 问题是在创建测试模块时,超类的属性未在 controller class 中初始化。

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

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属性将被初始化,并且代码可以工作。 但是在运行测试时,似乎测试模块没有初始化它(所以它是未定义的)。

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

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

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

最好关闭应用程序

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM