简体   繁体   English

如何在 Angular 中测试多个订阅?

[英]How to test multilple subscription in Angular?

In my Angular Unit Test I want to check whether myComponent.items$ have 0 results when I call subject myComponent.clearInput$.next() .在我的 Angular 单元测试中,当我调用 subject myComponent.clearInput$.next()时,我想检查myComponent.items$是否有 0 个结果。 Before that I want to ensure that there are some records.在此之前,我想确保有一些记录。 myComponent.items$ can be populated by myComponent.nameInput$.next("test") . myComponent.items$可以由myComponent.nameInput$.next("test")填充。

Unfortunately both subscription are triggered after both Subjects have been called, so myComponent.items$ is always 0.不幸的是,两个订阅都在调用两个主题后触发,因此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();
});

This is how is items$ is called by those Subjects这就是这些主题如何调用 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([]))
    )
);

In my unit tests, I rarely subscribe .在我的单元测试中,我很少subscribe . I use promise approach because then I can wait.我使用promise方法,因为这样我就可以等待。

Try this:尝试这个:

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();
});

I think that's what you want.我想这就是你想要的。 This way we can have blocking code and much better assertions.这样我们就可以拥有阻塞代码和更好的断言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM