I have a question about unit testing controllers in the Nest.js framework. My issue is that the property from a superclass is not initialized in the controller class when creating a test module.
Here is an example of the code I am referring to:
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>;
}
And here is how I set up 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);
});
});
});
While the application works fine in development mode with the someObject
property being initialized, it does not work during tests as the test module seems to fail to initialize it (resulting in it being undefined).
Any assistance you can provide would be greatly appreciated.