我有一个调用服务方法的组件。 当服务方法返回一个可观察值时,它就很好用了, 但是当我将其更改为Promise时,测试开始失败。
测试中的更改是:
工作:
测试:
[TestActionFilter]
组件:
services.AddMvc(options =>
{
options.Filters.Add(new TestActionFilter()); // an instance
});
更改为承诺后不起作用:
测试:
const getPackListSpy = ppackService.listPacks.and.returnValue( of(packListResult) );
it('should show pack list', fakeAsync(() => {
fixture.detectChanges();
tick(5000);
fixture.detectChanges();
const packsInView = fixture.nativeElement.querySelectorAll('.packName').length;
expect(packsInView).toBe(2);
}));
组件:
this.protocolPackService.listPacks()
.subscribe((packs) => {
this.packs = packs;
});
问题是,更改为Promise后,模板中的项目列表未显示任何数据(基于const getPackListSpy = ppackService.listPacks.and.returnValue( Promise.resolve(packListResult) );
)。在测试环境之外的两种情况下,该组件都可以正常工作。
任何想法可能出了什么问题吗?
组件代码:
this.packs = await this.protocolPackService.listPacks();
服务:
this.packs
答案 0 :(得分:0)
您必须使用一些方法来测试异步代码,例如fakeAsync/tick
from angular测试库:
it('should show items', fakeAsync(() => {
const { comp, el, fixture } = setup();
fixture.detectChanges();
tick(1000);
fixture.detectChanges();
expect(comp.packs.length).toBe(2);
}));
p.s。事实是,当您使用rxjs of
运算符模拟服务方法时,它将像同步代码一样工作,例如:
console.log(1);
of(2).subscribe(v => console.log(v));
console.log(3);
此代码将console.log:1、2、3。
但是当您使用Promise时,它将像异步代码一样工作,例如:
console.log(1);
Promise.resolve(2).then(v => console.log(v));
console.log(3);
此代码将console.log:1、3、2。
这就是为什么在使用Promises模拟服务方法时,必须牢记编写单元测试的原因,因为您正在处理异步代码。