angular - Angular:订阅中的单元测试变量
问题描述
我有一个在订阅中设置几个值的函数:
private getAllStatuses(): void {
this.refControllerService.getAllStatus().subscribe(data => {
this.StatusDTOList = data;
this.canEditDate = this.isEditableStatus();
this.isDEDUser = this.userAuthorisationService.isDEDUser();
this.initialised = true;
});
}
canEditDate
&isDEDUser
都是私有的,它们可以在另一个函数中访问:
public canEdit(): boolean {
return this.isDEDUser && this.canEditDate;
}
我试图在我的测试中设置这两个值,但到目前为止还没有任何外观:
it('StatusComponent canEdit should return false', () => {
spyOn(refControllerService, 'getAllStatus').and.returnValue(of({ canEditDate: false, isDEDUser: false }) as any)
spyOn(userAuthorisationServiceSpy, 'isDEDUser').and.returnValue(false)
component.ngOnInit();
expect(component.canEdit).toBeFalsy();
});
我尝试了几种不同的方法,并且搜索了类似的问题,我对角度比较陌生,有人可以解释一下我正在尝试什么吗?我可以在测试中设置该订阅中的值,以便我可以打开和关闭这些值canEdit()
吗?
解决方案
这个问题有很多不清楚的地方。我会勇敢地尝试回答它。
考虑到CanEdit is public and is the function under test
我们需要执行函数来测试它的结果。更改expect(component.canEdit)
为expect(component.canEdit())
.
我们看不到如何getAllStatuses
执行。我会使用它在ngOnInit
. 该函数使用对 Observable 的订阅以异步方式执行一些操作。这意味着我们需要等待执行。通常(并非总是如此)await fixture.whenStable()
足以等待异步内容的执行。我想这个测试将存档所需的结果:
it('StatusComponent canEdit should return false', async () => {
spyOn(refControllerService, 'getAllStatus').and.returnValue(of({ canEditDate: false, isDEDUser: false }) as any)
spyOn(userAuthorisationServiceSpy, 'isDEDUser').and.returnValue(false)
component.ngOnInit();
await fixture.whenStable();
expect(component.canEdit()).toBeFalsy();
});
推荐阅读
- java - 使用 FileInputStream 的有效文件的 FileNotFoundException
- javascript - 为什么这不画一个轨道而只画一个椭圆?
- php - PDO 不会执行,但在 phpmyadmin 中可以正常工作
- opencv - pytesseract 的实时检测速度非常慢,使用 python 的屏幕滞后很大
- gnuplot - 使用数组中数据的索引绘制多个图
- c++ - 如何修复 valgrind 启动时的致命错误(与 libc6-dbg 和 libc6-dbg:i386 连接)
- youtrack - 如何让客户经理在 Youtrack 中测试功能?
- javascript - 如何在通过 GraphQL 查询返回的降价中将 \n 格式化为换行符
- .net - SQL DataReader 给出“字符串或二进制数据将被截断”
- r - 如何在R中找到逆采样方法的逆