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 implements OnModuleInit {
protected someObject: SomeObject;
async onModuleInit() {
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.
In your test's before each you need to run the following
await module.init(); // this is where onModuleInit is called
It's also best to close the application
afterEach(async () => await module.close());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.