如何在Angular中测试multilple订阅?
在角度单元测试中,我想检查调用subject如何在Angular中测试multilple订阅?,angular,typescript,unit-testing,jasmine,angular-unit-test,Angular,Typescript,Unit Testing,Jasmine,Angular Unit Test,在角度单元测试中,我想检查调用subjectmyComponent.clearInput$.next()时,myComponent.items$是否有0个结果。在此之前,我想确保有一些记录myComponent.items$可以由myComponent.nameInput$.next(“test”)填充 不幸的是,这两个订阅都是在调用了这两个主题之后触发的,因此myComponent.items$始终为0 it("when control touched then clear input val
myComponent.clearInput$.next()
时,myComponent.items$
是否有0个结果。在此之前,我想确保有一些记录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();
});
这就是这些主题如何调用is 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([]))
)
);
在我的单元测试中,我很少订阅
。我使用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();
});
我想这就是你想要的。这样我们就可以有阻塞代码和更好的断言。我有一个错误:错误:超时-异步函数没有在5000ms内完成(由jasmine设置。默认超时时间间隔)好的,测试被困在承诺上。确保测试结构良好,组件也良好。我添加了console.log
,看看在…
log之后你看不到哪个,这是一个从未解决的承诺。console.log('after first wait…')代码>从不触发,这意味着项$
不会触发。nameInput$
和items$
有什么关系?我想这是因为nameInput$
是一个主题(不是ReplaySubject),所以调用toPromise()