用于测试 keyup 事件的 Angular 测试用例
下面提到的代码工作正常。它基本上合并两个事件,合并它们并对输入字段执行一些操作。问题是,我无法模拟或编写此代码的测试用例。谁能帮我解决这个问题吗?我正在使用 Angular 12。
<input #myname value="John Doe">
ngAfterViewInit() {
const scrollEvents$ = fromEvent(this.input.nativeElement, 'blur');
const keyEvents$ = fromEvent(this.input.nativeElement, 'keyup').pipe(
filter((e: KeyboardEvent) => e.keyCode === 13)
);
const allEvents$ = merge(scrollEvents$, keyEvents$);
allEvents$
.pipe(
takeUntil(this.unsubscribe$),
map((evt: any) => evt.target.value),
distinctUntilChanged()
)
.subscribe((text: string) => {
this.data = text;
});
}
Below mentioned code is working fine. which basically merge two events, merge them and do some operation on an input field. The problem is, I am not able to mock or write test cases for this code. Can anyone help me with this? I am using angular 12.
<input #myname value="John Doe">
ngAfterViewInit() {
const scrollEvents$ = fromEvent(this.input.nativeElement, 'blur');
const keyEvents$ = fromEvent(this.input.nativeElement, 'keyup').pipe(
filter((e: KeyboardEvent) => e.keyCode === 13)
);
const allEvents$ = merge(scrollEvents$, keyEvents$);
allEvents$
.pipe(
takeUntil(this.unsubscribe$),
map((evt: any) => evt.target.value),
distinctUntilChanged()
)
.subscribe((text: string) => {
this.data = text;
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果使用事件绑定,您将可以更轻松地编写测试, 像这样。然后,您可以针对该方法编写单元测试,和/或针对整个交互编写 E2E 测试。
You'll have a much easier time writing tests if you use event binding, like this. Then you can write unit tests against the method, and/or E2E tests against the whole interaction.
我一般倾向于创建“轻”组件和“胖”服务。
在这种情况下,这意味着将
pipe
逻辑隔离到服务中,然后通过依赖项注入将其传递到组件中,如下所示现在您可以更轻松地测试服务
MyService 这是大部分逻辑所在的地方。
What I tend to do in general is to create "light" components and "fat" services.
In this case, this would mean to isolate the
pipe
logic into a service which is then passed via dependency injection into the component, something like thisNow you can more easily test the service
MyService
which is where most of the logic resides.