我正在测试我的有角度的应用程序,并且有组件,如果表单无效,我想检查按钮是否被禁用。但是未添加disabled
属性。我在做什么错了?
我试图创建一个模拟表单,但也未得到验证。 还尝试将其本机设置为html并分派输入事件,这也不起作用:
it('submit button should be disabled if form is invalid', async() => {
const inputDe = fixture.debugElement.nativeElement.querySelector('input[name="amount"]');
const inputEl = inputDe.nativeElement;
inputDe.value = 'test';
inputDe.dispatchEvent(new Event('input'));
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('.btn-success').getAttribute('disabled')).toBeTruthy();
});
这是我的代码:
shopping-edit.component.ts
@Component({
selector: "app-shopping-edit",
templateUrl: "./shopping-edit.component.html",
styleUrls: ["./shopping-edit.component.css"]
})
export class ShoppingEditComponent implements OnInit, OnDestroy {
@ViewChild('form') form: NgForm;
}
shopping-edit.component.html
<div class="row">
<div class="col-xs-12">
<form (ngSubmit)="onSubmit()" #form="ngForm">
<div class="row">
<div class="col-sm-5 form-group">
<label for="name">Name</label>
<input ngModel name="name" type="text" id="name" class="form-control" required>
</div>
<div class="col-sm-2 form-group">
<label for="amount">Amount</label>
<input ngModel name="amount" type="number" id="amount" class="form-control" required pattern="^[1-9]+[0-9]*$" >
</div>
</div>
<div class="row">
<div class="col-xs-12">
<button class="btn btn-success" type="submit" [disabled]="!form.valid">{{ editMode ? 'Update' : 'Add' }}</button>
</div>
</div>
</form>
shopping-edit.component.spec.ts
describe('ShoppingEdit component', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
FormsModule
],
declarations: [ShoppingEditComponent]
});
fixture = TestBed.createComponent(ShoppingEditComponent);
});
it('submit button should be disabled if form is invalid', async() => {
// const testForm = <NgForm>{
// valid: false
// };
setTimeout(() => {
fixture.debugElement.componentInstance.form.setValue({name: '', amount: 'a555'});
}, 1000);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('.btn-success').getAttribute('disabled')).toBeTruthy();
});
});
有什么想法吗?