如何正确测试Angular组件中类型为Observable<boolean>的属性
问题原因
当前测试报错是因为isProductListEmpty是Observable布尔流对象,不是直接的布尔值,你直接对Observable对象本身做布尔值断言自然会匹配失败,需要先拿到流发射的布尔值再做断言。
正确测试用例写法
以下是两种常用的可直接运行的测试写法,注意要先对齐你代码里的属性名大小写,避免赋值不生效:
写法1:订阅+done回调(兼容性最好)
// 顶部导入rxjs操作符 import { first } from 'rxjs'; it('should return true when List is empty', (done) => { // 注意属性名要和组件实际定义对齐,原组件定义的是首字母大写的ProductListLength component.ProductListLength = 0; fixture.detectChanges(); component.isProductListEmpty.pipe(first()).subscribe(res => { expect(res).toBeTrue(); done(); // 通知Jasmine异步测试执行完毕 }) }) it('should return false when List not empty', (done) => { component.ProductListLength = 2; fixture.detectChanges(); component.isProductListEmpty.pipe(first()).subscribe(res => { expect(res).toBeFalse(); done(); }) })
写法2:async/await写法(更简洁,适合RxJS 7+版本)
// 顶部导入工具方法 import { firstValueFrom } from 'rxjs'; it('should return true when List is empty', async () => { component.ProductListLength = 0; fixture.detectChanges(); const res = await firstValueFrom(component.isProductListEmpty); expect(res).toBeTrue(); }) it('should return false when List not empty', async () => { component.ProductListLength = 2; fixture.detectChanges(); const res = await firstValueFrom(component.isProductListEmpty); expect(res).toBeFalse(); })
额外修正提示
你原组件代码存在语法括号错位问题,修正后可正常运行:
import { Observable } from "rxjs"; import { OnInit } from '@angular/core'; export class ProductComponent implements OnInit { ProductListLength: number; isProductListEmpty: Observable<boolean>; ngOnInit(): void { if(this.ProductListLength === 0) { this.isProductListEmpty = new Observable((observer) => observer.next(true)) } else { this.isProductListEmpty = new Observable((observer) => observer.next(false)) } } }
内容的提问来源于stack exchange,提问作者LucasOAK
相关产品推荐
相关产品推荐

