4 javascript testing typescript jestjs nestjs
我有一个关于 Nest.js 框架中的单元测试控制器的问题。问题是,在创建测试模块时,来自超类的属性未在控制器类中初始化。
这是我正在讨论的示例代码:
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>;
}
Run Code Online (Sandbox Code Playgroud)
这就是我创建测试的方式
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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
现在,如果我在开发模式下运行应用程序,该someObject
属性将被初始化,并且代码可以工作。但是当运行测试时,测试模块似乎没有初始化它(所以它是未定义的)。
非常感谢任何形式的帮助。
sou*_*rri 15
在每次测试之前,您需要运行以下命令
await module.init(); // this is where onModuleInit is called
Run Code Online (Sandbox Code Playgroud)
最好也关闭该应用程序
afterEach(async () => await module.close());
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4031 次 |
最近记录: |