【发布时间】:2020-07-31 04:45:53
【问题描述】:
基于https://angular.io/guide/reactive-forms 中的第一个示例,我创建了以下哑组件:
@Component({
selector: 'app-name-editor',
templateUrl: './name-editor.component.html',
styleUrls: ['./name-editor.component.css']
})
export class NameEditorComponent {
name = new FormControl('');
@Output('submitted') submitted = new EventEmitter<string>();
onSubmit() { this.submitted.emit(this.name.value); }
}
... 我想为此编写一个单元测试来验证是否提交了一个值。这使用了 https://angular.io/guide/testing#component-inside-a-test-host 中建议的 TestHost :
@Component({
template: `
<app-name-editor (submitted)=onSubmit($event)>
</app-name-editor>
`})
class TestHostComponent {
submitted: string;
onSubmit(data: string) { this.submitted = data; }
}
describe('NameEditorComponent', () => {
let testHost: TestHostComponent;
let fixture: ComponentFixture<TestHostComponent>;
let editorDebugElt: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ NameEditorComponent, TestHostComponent ]
});
fixture = TestBed.createComponent(TestHostComponent);
testHost = fixture.componentInstance;
editorDebugElt = fixture.debugElement.query(By.directive(NameEditorComponent));
fixture.detectChanges();
});
it('should capture data', () => {
const compiled = fixture.debugElement.nativeElement;
const nameInput = compiled.querySelector('input[type="text"]');
expect(nameInput).toBeTruthy();
nameInput.value = 'This is a test';
fixture.detectChanges();
// Find submit button
const submitInput = compiled.querySelector('input[type="submit"]');
expect(submitInput).toBeTruthy();
// Trigger click action
expect(testHost.submitted).toBeFalsy();
submitInput.click();
// Submitted
expect(testHost.submitted).toBe('This is a test');
});
});
测试失败,但我不明白为什么。输入中填充了测试结果下方所示的值。任何帮助将不胜感激。
【问题讨论】:
标签: angular angular-reactive-forms angular9 angular-unit-test