gpt4 book ai didi

angular - 如何使用 Observable Input 测试 Angular 组件

转载 作者:太空狗 更新时间:2023-10-29 17:58:30 24 4
gpt4 key购买 nike

我正在尝试测试一个 Angular Component,它基本上接收一个 Observable 并根据从该 Observable 发出的值更改其 template .这是一个简化版本:

@Component({
selector: 'async-text',
template: `
<span>{{ text | async }}</span>
`,
})
export class AsyncTextComponent {
@Input() text: Observable<string>;
}

我想测试一下,目前这就是我所拥有的,使用 rxjs-marbles (虽然这不是必须的)。

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AsyncTextComponent } from './async-text.component';

describe('AsyncTextComponent', () => {
let component: BannerComponent;
let fixture: AsyncTextComponent<AsyncTextComponent>;

it('...',
marbles(m => {
fixture = TestBed.createComponent(AsyncTextComponent);
component = fixture.componentInstance;
component.text = m.cold('-a-b-c|', {
a: 'first',
b: 'second',
c: 'third',
});

fixture.detectChanges();
expect(component.nativeElement.innerHTML).toContain('first');

fixture.detectChanges();
expect(component.nativeElement.innerHTML).toContain('second');

fixture.detectChanges();
expect(component.nativeElement.innerHTML).toContain('third');
})
);
});

显然这行不通。我的问题是我没有找到在每个 expect 之间将 TestScheduler 推进给定数量的“帧”的方法。

如何手动跳帧?或者,是否有更好的方法来测试上述组件/场景(接收 Observable 的 Angular 组件,我想测试它在给定 Observable 发射的情况下的行为)。

我确实看到了 .flush(),但正如记录的那样,它运行了所有 Observable 的发射,所以我会到达最终状态,并且无法测试状态之间的不同转换.

谢谢

最佳答案

您不必使用任何库来测试它。更重要的是,您可以在 Angular 的上下文之外对其进行测试。

无论如何,这里是解释。

为了对此进行测试,我建议使用变量。但如果你想坚持你的方法,你应该坚持下去。

it('should display first', done => {
// Mock your component
component.text = Observable.of('first');
// Detect template changes
fixture.detectChanges();
// trigger a change detection, just in case (try without, you never know)
setTimeout(() => {
// Get the element that is displaying (tip: it's not your whole component)
const el = fixture.nativeElement.querySelector('span');
// Test the innet text, not the HTML
// Test with includes, in case you have spaces (but feel free to test without includes)
expect(el.innerText.includes('first')).toEqual(true);
// End your test
done();
});
});

关于angular - 如何使用 Observable Input 测试 Angular 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50512031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com