Angular 在karma中测试subscribe会给出类型为'的错误参数;可观察<&燃气轮机';不可分配给类型为';认购';
我有这个方法Angular 在karma中测试subscribe会给出类型为'的错误参数;可观察<&燃气轮机';不可分配给类型为';认购';,angular,unit-testing,testing,jasmine,karma-jasmine,Angular,Unit Testing,Testing,Jasmine,Karma Jasmine,我有这个方法 loadCombos(): void { this.combosService.accounts$.subscribe( (data: any) => { this.list = data; } } ); } 这是我目前的测试: it('should test loadCombos executions ', (done) => { combosService = TestBed.inject(CombosService
loadCombos(): void {
this.combosService.accounts$.subscribe(
(data: any) => {
this.list = data;
}
}
);
}
这是我目前的测试:
it('should test loadCombos executions ', (done) => {
combosService = TestBed.inject(CombosService);
spyOn(combosService.accounts$, 'subscribe').and.returnValue(of(mockList));
component.loadCombos();
expect(component.list).not.toBeNull();
done();
});
如何在测试中使用模拟列表,目前我得到的是一个可观察的,但它需要一个引用,但我不知道如何使用。这里有几个错误 一个
subscribe()
不会返回Observable
它返回一个subscribe
,就像错误所说的那样。您可以在测试中返回newsubscription()
,但这没有任何意义
如果您想模拟帐户$
的返回。正确的方法是更改模拟实现的组合服务
测试它的一种快速方法是直接覆盖帐户
(如果未标记为只读)
但我不会这样做,因为如果从某种按钮调用loadCombos()
,则该实现是错误的
编辑:就我个人而言,我喜欢在
fakeAsync
调用中测试可观察对象:我也尝试过,我得到了以下错误:“accounts$”类型的参数不能分配给“never”类型的参数。这是一个继承的项目,我必须进行测试,我没有太多的选项,也不能引入新的东西,所以我不能使用FakeAsync FakeAsync已经随Angular提供了,没有什么可更改的。另外,我刚刚意识到,accounts$
不是一个函数。Sorry@monxas现在看一看
it('should test loadCombos executions ', (done) => {
combosService = TestBed.inject(CombosService);
combosService.accounts$ = of(mockList);
component.loadCombos();
expect(component.list).not.toBeNull();
done();
});