[英]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.