【发布时间】:2020-09-01 20:54:50
【问题描述】:
所以我尝试添加两个测试以确保实际上为属性设置了两个绑定。不知道我在这里缺少什么,但感觉我已经很接近了。
这里是html:
<input [(ngModel)]="value" (change)="onChange()"/>
这里是组件类:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'cs-string-field',
templateUrl: './string-field.component.html',
styleUrls: ['./string-field.component.scss']
})
export class StringFieldComponent implements OnInit {
@Input() value: string;
@Output() change = new EventEmitter<string>();
constructor() { }
ngOnInit(): void {
}
onChange = () => this.change.emit(this.value);
}
最后但并非最不重要的是我的测试。最后一个失败了:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { StringFieldComponent } from './string-field.component';
import { FormsModule } from '@angular/forms';
describe('StringFieldComponent', () => {
let component: StringFieldComponent;
let fixture: ComponentFixture<StringFieldComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ StringFieldComponent ],
imports: [FormsModule]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(StringFieldComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should have an input tag with type text', () => {
const sut = fixture.nativeElement
.querySelector('input[type="text"]');
expect(sut).toBeTruthy();
});
it('should emit a value on change', done => {
const value = "Pretty Kitty";
const event = new Event('change');
component.value = value;
fixture.detectChanges();
const ele = fixture.nativeElement
.querySelector('input[type="text"]');
component.change.subscribe(res => {
expect(res).toBe(value);
done();
})
ele.dispatchEvent(event);
});
it('should update value on input', done => {
const value = "Pretty Kitty";
const event = new Event('change');
component.value = '';
fixture.detectChanges();
const ele = fixture.nativeElement
.querySelector('input[type="text"]');
component.change.subscribe(res => {
expect(res).toBe(value);
done();
})
ele.value = value;
ele.dispatchEvent(event);
});
});
我觉得我在这里遗漏了一些非常简单的东西,但是组件上没有设置值。
【问题讨论】:
标签: angular jestjs two-way-binding