【发布时间】:2018-12-29 23:56:39
【问题描述】:
我有一个简单的案例。 Angular 应用程序的标准AppComponent 包含一个ChildComponent,它在它自己的模块ChildModule 中定义。
ChildComponent的模板很简单
<div class="child" (click)="testClick($event)"></div>
ChildComponent 有一个更简单的testClick(event) 方法,它只在控制台上记录一条消息。
testClick(event) {
console.log(event);
}
现在我想在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);
}));
});
测试工作正常,特别是第二个测试按预期在控制台上打印clicked 消息。
现在我有点复杂了ChildComponent。我想使用fromEvent 运算符和ViewChild 在click 事件上创建一个Observable。
所以代码变成了
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));
}
}
我用ng serve 启动开发服务器,我看到控制台上打印了2 条消息,一条是testClick 方法,另一条是订阅testClick$ Observable。
如果我现在运行与以前相同的测试,我希望在控制台上也能看到同样的两条消息。相反,我只看到testClick 方法打印的消息。订阅的消息,即'test click in child',没有出现,这意味着当child.triggerEventHandler('click', 'clicked');被执行时,ObservabletestClick$没有发出。
如何使使用fromEvent 创建的 Observables 在 jasmine 测试中工作?我做错了什么?
【问题讨论】:
标签: angular jasmine rxjs angular-test