如何在Jasmine中访问模板引用/变量?
form.component.html
<form #f="ngForm" class="form form-profession" novalidate>...
<div class="error-group" *ngIf="f.invalid">error</div>
form.component.ts
export class FormComponent implements OnInit {
@ViewChild('f') f: NgForm;
constructor(
private router: Router
) { }
ngOnInit() {
}
onSubmit(f) {
if (f.valid) {
// do stuff
}
}
form.component.spec.ts
it('should display errors when form is invalid', () => {
fixture.componentInstance.f.invalid = true;
expect(fixture.nativeElement.querySelector('.error-group')).not.toBeNull();
});
我收到此错误 “ [ts]无法分配给'valid',因为它是常量或只读属性。”
答案 0 :(得分:1)
尝试这样做。
it('should show error message when form is invalid', () => {
const form = fixture.componentInstance.f; // get the form instance through the component.
form.form.setErrors({required: true}); // making the form invalid
fixture.detectChanges(); // trigger a change detection cycle for the component
expect(fixture.nativeElement.querySelector('.error-group').textContent).toContain('sss');
expect(form.valid).toBeFalsy();
});
答案 1 :(得分:0)
您可以使用它来访问组件fixture.debugElement.query(By.directive(ClassOfTheSearchedComponent))