如何模拟Angular中单元测试的父类方法



我正在为一个类编写单元测试,该类在运行时扩展另一个类并调用父方法。既然我不想处理父类,有什么方法可以模拟那个方法调用吗?我尝试了多种方法,但在工作中一无所获

class A {
doSomething(){
console.log(123);
}
}
class B extends A {
work(){
this.doSomething();
}
}

如何在B类的单元测试中模拟这个函数调用并返回其他内容?

我尝试过以下几种:

spyOn(b,'doSomething');
spyOn(Object.getPrototypeOf(b),'doSomething');

没有错误,它只是不断调用原始父方法

您可以做的,但我不建议这样做,就是在类B中存根父方法本身。

我不推荐这种方法,因为您会在正在进行单元测试的类中插入一些内容。我宁愿在这个父方法中执行存根操作。

但是,如果你真的想终止这种方法,你可以沿着这些路线做一些事情:

describe('DataService', () => {
let service: DataService;
beforeEach(async(() => {
TestBed.configureTestingModule({ providers: [DataService] });
}));
beforeEach(() => {
service = TestBed.get(DataService); // would be inject in newer angular versions
});
it('test case 2', () => {
spyOn(service as any, 'parentMethod').and.returnValue(5);
expect(service.getData()).toEqual(5);
});
});

其中DataService将是


@Injectable({
providedIn: 'root'
})
export class DataService extends AbstractDataService {
constructor() {
super();
}
getData() {
return this.parentMethod();
}
}

AbstractDataService

@Injectable({
providedIn: 'root'
})
export class AbstractDataService {
constructor() { }
parentMethod() {
console.log('parent method');
return null;
}
}

也适用于组件。但是:不建议在测试对象内部模拟方法

describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent, AbstractAppComponent],
schemas: [NO_ERRORS_SCHEMA],
bootstrap: [AppComponent]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
});
it('should mock method', () => {
spyOn(component as any, 'abstractMethod').and.returnValue(10);
fixture.detectChanges();
expect(component.myMethod()).toEqual(10);
});    
});

Stacklitz,包含服务和组件的测试用例

最新更新