【发布时间】:2021-01-24 21:45:37
【问题描述】:
考虑以下代码:
app.component.ts
@Component({
selector: 'app-component',
templateUrl: './app-component.html',
styleUrls: ['./app-component.scss']
})
export class AppComponent implements OnInit {
constructor(
private userService: UserService
) { }
ngOnInit() {}
}
app.component.html
<div *ngIf="userService.isUserLoggedIn$ | async">
<span class="username">{{(userService.user$ | async)?.name}}</span>
</div>
这是对我的一个组件的简化。 我试着写一个基本的单元测试:
it('should display the username', () => {
userService.isUserLoggedIn$ = cold('-a|', {a: true});
userService.user$ = cold('-a|', {a: {name: 'foo'});
fixture.detectChanges();
getTestScheduler().flush();
fixture.detectChanges();
const el = fixture.debugElement.query(By.css('.username')).nativeElement as HTMLSpanElement;
expect(el.innerText.trim()).toBe('foo);
});
我正在使用 jasmine marbles 库。
问题是跨度没有正确的值,它总是空的。 我猜是因为 2 个嵌套的异步管道。刷新 observables 后,ngIf 条件变为 true,创建 span 并创建 user$ 的新订阅。但是因为 observable 完成了,span 会是空的。
我不确定这是否是正确的解释...
我的问题是我应该如何测试这种场景?
谢谢!
【问题讨论】:
标签: angular rxjs jasmine angular-unit-test jasmine-marbles