0

在我的 Angular 单元测试中,我想myComponent.items$在调用 subject 时检查是否有 0 个结果myComponent.clearInput$.next()。在此之前,我想确保有一些记录。myComponent.items$可以由 填充myComponent.nameInput$.next("test")

不幸的是,两个订阅都是在两个主题都被调用后触发的,所以myComponent.items$总是 0。

it("when control touched then clear input value", done => {

    myComponent.items$.pipe(first()).subscribe(result => {
        expect(result.length).toBe(2); 
        // it's always 0 because of myComponent.clearInput$.next(); from last line
    })
    myComponent.nameInput$.next("test");

// Now should wait after code from above will finish then the rest should be executed after that.

    myComponent.items$.pipe(first()).subscribe(result => {
        expect(result.length).toBe(0);
        done(); // test should be finished here
    })
    myComponent.clearInput$.next();
});

这就是那些主题调用 items$ 的方式

this.items$ = merge(
    this.nameInput$.pipe(
        switchMap((name: string) =>
            iif(() => this._partyType === "PT",
                this.someService.getByName(name),
                this.otherService.getByOtherName(name)
            )
        )
    ),
    this.clearInput$.pipe(
        switchMapTo(of([]))
    )
);
4

1 回答 1

0

在我的单元测试中,我很少subscribe. 我使用promise方法是因为我可以等待。

尝试这个:

it("when control touched then clear input value", async done => {
   myComponent.nameInput$.next("test");
   console.log('first await...');
   const result = await myComponent.items$.pipe(take(1)).toPromise();
   console.log('after first await...');
   expect(result.length).toBe(2);

   myComponent.clearInput$.next();
   console.log('second await...');
   const newResult = await myComponent.items$.pipe(take(1)).toPromise();
   console.log('after second await...');
   expect(newResult.length).toBe(0);
   done();
});

我想这就是你想要的。这样我们就可以拥有阻塞代码和更好的断言。

于 2020-03-13T17:06:52.317 回答