ben*_*ngr 5 rxjs angular angular-test rxjs6
我正在尝试测试一个 Angular Component,它基本上接收一个Observable并template根据该 Observable 发出的值更改它。这是一个简化版本:
@Component({
selector: 'async-text',
template: `
<span>{{ text | async }}</span>
`,
})
export class AsyncTextComponent {
@Input() text: Observable<string>;
}
Run Code Online (Sandbox Code Playgroud)
我想测试一下,目前这就是我所拥有的,正在使用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');
})
);
});
Run Code Online (Sandbox Code Playgroud)
显然这行不通。我的问题是我没有找到一种方法来在每个expect.
如何手动跳帧?或者,是否有更好的方法来测试上述组件/场景(接收 的 Angular 组件,Observable我想测试它在 Observable 发出的情况下的行为)。
我确实看到了.flush(),但正如记录的那样,它运行所有 Observable 的发射,所以我会到达最终状态,并且无法测试状态之间的不同转换。
谢谢
小智 2
您不必使用任何库来测试它。更重要的是,您可以在 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();
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2975 次 |
| 最近记录: |