如何在Angular 6单元测试中测试输入元素和事件

问题描述

我具有以下单元测试功能。在第三行中,测试失败,因为我似乎在模拟该事件,该事件被错误地传递给该函数。

  unitTypeChanged(event: Event) {
    const target: HTMLSelectElement = event.target as HTMLSelectElement;
    if (this._unitsMap.has(target.value)) {
      this.units$ = of(this._unitsMap.get(target.value));
    } else {
      this.setUnits(target.value);
    }
  }

在测试中,我正在将事件调度到通用选择,但是我仍然得到null值,并且无法通过测试。

it('unitTypeChanged',() => {
  const selectElement: HTMLSelectElement = document.createElement('select');
  selectElement.value = 'Paul';
  const changeEvent: Event = new Event('change');
  selectElement.dispatchEvent(changeEvent);

  component.unitTypeChanged(changeEvent);
});

这是测试设置

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule,BrowserAnimationsModule,HttpClientTestingModule,TranslateModule.forRoot(),SharedModule],declarations: [],providers: [{ provide: UnitService,useValue: { getUnitsByUnitTypeId: (arg1: string) => of([]) } }]
    }).compileComponents();

    // Language service static mock
    LanguageService.languages = [{ id: 'de',displayName: 'Deutsch',isNeutral: true }];

    fixture = TestBed.createComponent(EditorRequirementFormComponent);
    component = fixture.componentInstance;
    // Standard initializations
    component.dataChanges = new BehaviorSubject<Observable<any>>(of(null));
    fixture.detectChanges();
  });

这是单元测试的错误消息。

SUMMARY:
√ 0 tests completed
i 333 tests skipped
× 1 test failed

FAILED TESTS:
    × unitTypeChanged
      HeadlessChrome 84.0.4147 (Windows 10.0.0)
    TypeError: Cannot read property 'value' of null
        at EditorRequirementFormComponent.value [as unitTypeChanged] (http://localhost:9876/_karma_webpack_/src/app/modules/content/editor/editor/editor-tabs/editor-requirement-form/editor-requirement-form.component.ts:84:39)
        at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/modules/content/editor/editor/editor-tabs/editor-requirement-form/editor-requirement-form.component.spec.ts:81:15)
        at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:359:1)
        at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:308:1)
        at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:358:1)
        at Zone.run (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:124:1)
        at runInTestZone (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:561:1)
        at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:576:1)

解决方法

因此,基本问题是在调度此类事件时未设置event.target

selectElement.dispatchEvent(changeEvent);

由于事件接口的target属性为只读,因此我们现在不再使用上层解决方案,而是使用Object.defineProperty来操作事件对象并覆盖目标。

Object.defineProperty(changeEvent,'target',{writable: false,value: selectElement});

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...