【问题标题】:Angular Unit Test - nested async pipesAngular Unit Test - 嵌套的异步管道
【发布时间】: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


    【解决方案1】:

    TestBed.configureTestingModule 之后定义userService.isUserLoggedIn$ = cold('-a|', {a: true});userService.user$ = cold('-a|', {a: {name: 'foo'}); 为时已晚。这些值已经被注入,isUserLoggedIn$user$ 是“静态”值。将它们设置在稍后的时间点不会告诉可观察序列来更新它(不会发生排放)。

    当您模拟userService 时,在TestBed.configureTestingModule 之前附加isUserLoggedIn$user$

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 2019-04-07
      相关资源
      最近更新 更多