【发布时间】:2020-07-22 14:08:48
【问题描述】:
我有一个在每个网格组件中使用的通用基类。
现在,我有网格组件的规范,但我想在单独的基本规范文件中添加基类的规范。
其背后的动机是删除重复代码并为基网格制作通用规范文件,该文件将为使用基类的每个网格提供服务。
我卡住了,我无法在基本规范文件中创建规范。基本上我想要一个函数下的基本文件中的所有规范,当这个函数从具有该组件的子类调用时,它应该返回该类的所有规范。
这是我目前拥有的以及我尝试过的。
组件层:
export class MyComponent extends BaseGrid<MyEntity> {
... (and all other code like constructor and methods)...
}
基础层:
export class BaseGrid<T> {
public async getData(): Promise<void> { ... }
}
... and 100 other functions
组件规格:
describe('MyComponent ', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [
...
],
providers: [
],
}).compileComponents().then(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
}));
// here I created a reference function for my base class spec
// Now, This is working but I don't want this **describe** and **it** to be here,
// it should be in the base file. so I can remove this repetitive code from all components.
// And From here I just want to call one function let's say a **baseGridSpecs(component)**,
// that will load all the specs of base class in this component.
describe('Should initialize Base grid', () => {
it('should have proper component.', () => {
const baseGridSpecs = new BaseGridSpecs<MyComponent>();
baseGridSpecs.runBaseGridTests(component);
baseGridSpecs.checkGetDataDefined(component);
});
});
});
基本规格:
export class BaseGridSpecs<T> {
runBaseGridTests(component: any): void {
expect(component).toBeTruthy();
}
checkGetDataDefined(component: any): void {
expect(component.getData).toBeDefined();
}
}
这个结构对我来说很好用,但它没有用,因为我的 describe 和 it 仍在主要组件规范文件中。
我想要实现的只是调用基本规范函数,如
baseGridSpecs.runBaseGridTests(component);,它应该为给定的通用组件呈现所有describe和it规范。
任何帮助将不胜感激...
【问题讨论】:
-
如果所有子类都应该通过相同的测试套件来实际测试基类的逻辑,那么似乎可以只针对基类运行一次该套件,并且只留下特定于其套件中的子类测试.如果重点是确保所有子类共享某些行为,您可以编写规范,在其中列出子类并在每个子类的循环中运行规范。
-
@Shlang:是的,动机是所有子类都应该通过相同的测试套件来实际测试基类的逻辑,但我无法在基本规范文件中创建规范。基本上我想要一个函数下的基本文件中的所有规范,当这个函数从具有该组件的子类调用时,它应该返回该类的所有规范。
标签: angular typescript unit-testing jasmine karma-runner