Pic*_*cci 6 jasmine rxjs angular angular-test
我有一个简单的案例。AppComponentAngular 应用程序的标准包含ChildComponent在其自己的模块中定义的ChildModule。
的模板ChildComponent很简单
<div class="child" (click)="testClick($event)"></div>
Run Code Online (Sandbox Code Playgroud)
ChildComponent有一个更简单的testClick(event)方法,它只在控制台上记录一条消息。
testClick(event) {
console.log(event);
}
Run Code Online (Sandbox Code Playgroud)
现在我想建立一个AppComponent模拟点击的测试ChildComponent。
这是测试的代码
describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>;
let app: AppComponent;
let child: DebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ ChildModule ],
declarations: [
AppComponent
],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
app = fixture.debugElement.componentInstance;
child = fixture.debugElement.query(By.css('.child'));
fixture.detectChanges();
});
it(`should create the child'`, async(() => {
expect(child).toBeTruthy();
}));
it(`clicks on the child and the relative Observable emits`, async(() => {
setTimeout(() => {
child.triggerEventHandler('click', 'clicked');
}, 100);
}));
});
Run Code Online (Sandbox Code Playgroud)
测试工作,特别是第二个测试clicked按预期在控制台上打印消息。
现在我有点复杂了ChildComponent。我想click使用fromEvent操作符 and为事件创建一个 Observable ViewChild。
所以代码变成
export class ChildComponent implements AfterViewInit {
@ViewChild('child') private childElement: ElementRef;
ngAfterViewInit() {
const testClick$ = fromEvent(this.childElement.nativeElement, 'click');
testClick$.subscribe(d => console.log('test click in child', d));
}
}
Run Code Online (Sandbox Code Playgroud)
我启动了开发服务器,ng serve我看到控制台上打印了 2 条消息,一条是testClick方法,另一条是testClick$Observable的订阅。
如果我现在运行与以前相同的测试,我希望在控制台上也能看到相同的两条消息。相反,我只看到该testClick方法打印的消息。订阅的消息,即'test click in child',没有出现,这意味着 ObservabletestClick$在child.triggerEventHandler('click', 'clicked');执行时没有发出。
如何fromEvent在jasmine测试中使用工作创建 Observables ?我究竟做错了什么?
最终我找到了一种可以在fromEventRxJ 函数中使用的触发事件的方法。
该解决方案受到这篇文章的启发。
这个想法是,为了能够从 DOM 事件创建事件流,您必须dispatchEvent在 DebugElement 包装的本机元素上使用该方法。
所以,而不是做
child.triggerEventHandler('click', 'clicked');
Run Code Online (Sandbox Code Playgroud)
你必须使用类似的东西
child.nativeElement.dispatchEvent(new MouseEvent('click', {...});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2218 次 |
| 最近记录: |