mardi 24 septembre 2019

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

I have a question regarding unit testing controllers in Nest.js framework. Problem is that property from a superclass is not initialized in the controller class when creating a test module.

This is a sample code I'm talking about:

export class MyController extends SomeOtherController {

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

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

}

export abstract class SomeOtherController {

    protected someObject: SomeObject;

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

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

And this is how I've created my test

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);
    });
  });
});

Now, if I were to run the application in development mode, the someObject property would get initialized, and code works. But when running tests, it seems like the test module is not initializing it (so it is undefined).

Any sort of help is much appreciated.

Aucun commentaire:

Enregistrer un commentaire