Angular 2/4 组件单元测试单击事件不会触发更改



>我正在尝试对角度 2/4 组件进行单元测试,并想看看单击按钮元素是否会导致所需的更改。但是我无法触发点击事件。

组件

import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } 
from '@angular/core';
@Component({
selector: 'input-filter',
template: `
<div class="input-widget">
<div class="icon-filter"></div>
<input
type="text"
[value]="value"
(input)="filter.emit($event.target.value)"
placeholder="... filter"/>
<span (click)="clear()" class="clear icon-clear-field_S"></span>
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class InputFilterComponent {
@Input() value;
@Output() filter = new EventEmitter(false);
clear() {
this.value = '';
this.filterBoxes = [];
this.filter.emit(this.value);
}
}

测试内容

import { TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { InputFilterComponent } from './input-filter.component';
import { Component} from '@angular/core';
const testValue = 'test1234';
@Component({
selector  : 'test-cmp',
template  : `<input-filter [value]="testValueC"></input-filter>`,
})
class TestCmpWrapper {
testValueC = testValue; // mock input
}
describe('input-filter.component', () => {
let fixture;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [TestCmpWrapper, InputFilterComponent],
});
fixture = TestBed.createComponent(TestCmpWrapper);
});
it('should clear on click', () => {
let testHostComponent = fixture.componentInstance;
const el = fixture.debugElement.nativeElement;
// both methods to trigger click do not work
el.querySelector('.clear').click(); 
el.querySelector('.clear').dispatchEvent(new Event('click'));
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(el.querySelector('input').value).toBe('');
})
});
});
HeadlessChrome 0.0.0

(Linux 0.0.0( input-filter.component 应清除 单击失败,预期"test1234"为"。

尝试下面的代码。您也可以在不添加假异步的情况下执行此操作。只需添加 fixture.detectChanges((;在测试代码之前

import { TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { InputFilterComponent } from './input-filter.component';
import { Component } from '@angular/core';
const testValue = 'test1234';
@Component({
selector: 'test-cmp',
template: `<input-filter [value]="testValueC"></input-filter>`,
})
class TestCmpWrapper {
testValueC = testValue; // mock input
}
fdescribe('input-filter.component', () => {
let fixture;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [TestCmpWrapper, InputFilterComponent],
});
fixture = TestBed.createComponent(TestCmpWrapper);
});
it('should clear on click', () => {
fixture.detectChanges();
const testHostComponent = fixture.componentInstance;
const el = fixture.debugElement.nativeElement;
// both methods to trigger click do not work
el.querySelector('.clear').click();
el.querySelector('.clear').dispatchEvent(new Event('click'));
fixture.detectChanges();
expect(el.querySelector('input').value).toBe('');
});
});

相关内容

  • 没有找到相关文章