angular - 从 Angular 5 测试中触发输入事件

标签 angular jestjs dom-events

我一直在尝试并查看 Angular 文档一个多小时,但仍然无法通过此测试。我正在使用 Jest(与 Jasmine 非常相似)。问题是,当我ng serve 时,它正在应用程序中运行,我就是无法为它编写通过测试!

HTML 模板

 id="typeahead-plan"
   placeholder="search"
   type="text" class="form-control br--top"
   [(ngModel)]="selections.clientId"
   [ngbTypeahead]="searchClients"
   (input)="resetFileId()"
   (blur)="filterFileIds()"
   (keyup.enter)="filterFileIds()"
   (selectItem)="selectClientPlan($event.target.value)" />

规范

test('Submit button is disabled when changing plan', () => {
  component.resetFileId = jest.fn();
  fixture.detectChanges();
  const submitEl = fixture.debugElement.query(
    By.css('button[data-test=submit]')
  );
  const planInputEl = fixture.debugElement.query(By.css('#typeahead-plan'));
  expect(submitEl.nativeElement.attributes['disabled']).not.toBeDefined();

  planInputEl.nativeElement.value = 'd';
  planInputEl.triggerEventHandler('input', null);
  fixture.detectChanges();
  expect(component.resetFileId).toHaveBeenCalled();
  expect(submitEl.nativeElement.attributes['disabled']).toBeTruthy();
});

测试表明 spy 应该被调用,但它从未被调用,所以这让我认为我没有正确触发输入事件。如果我注释掉 toHaveBeenCalled 断言,那么下一个断言就会失败,因为提交按钮没有 disabled 属性。同样,手动点击 UI 一切正常,只是在测试中没有。当我尝试学习如何编写测试时,这种事情不断出现,这真的很令人沮丧,并减慢了我的开发速度。

最佳答案

看起来我必须在引发事件时包含一个带有目标的对象。 Angular docs状态:

The test assumes (correctly in this case) that the runtime event handler—the component's click() method—doesn't care about the event object.

Other handlers are less forgiving. For example, the RouterLink directive expects an object with a button property that identifies which mouse button (if any) was pressed during the click. The RouterLink directive throws an error if the event object is missing.

但是,他们没有说明“其他处理程序”是什么,或者他们需要什么,这似乎是一个明显的遗漏。

所以,如果我这样做:inputEl.triggerEventHandler('input', { target: inputEl.nativeElement }); 然后事件触发,它检测到函数被调用。

关于angular - 从 Angular 5 测试中触发输入事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51028892/

相关文章:

angular - 在 Stackblitz Angular 项目中使用 Object.values()

javascript - 将调用对象的 id 传递给 onclick 事件

angular - 无法使用 SystemJS 启动 ui-router 混合应用程序

angular - ionic 3 : Modal Controller - Get component Instance

javascript - 如何在 Jest 中检查 Map 对象键

jestjs - Stencil 组件上的 Jest 测试不应用变量更改

AngularJS:在模式取消时恢复形式?

JavaScript 文本框换行

Angularfire2 - 带参数的查询表

javascript - 如何用 jest 测试 unhandledRejection/uncaughtException 处理程序