我有一个使用Angular Material组件的表单。我想测试表单是否提交了预期的数据。我将在下面发布代码的简化版本,但基本上,我的测试会更改输入的值并模拟对“提交”按钮的单击。我能够确认输入值确实发生了更改,并且提交了表单,但问题是,即使我的断言通过了输入值发生了更改,也就是说它与一个空对象一起提交了。为什么它会识别出输入值已更改,却提交了表单,好像没有更改一样?我是刚开始测试Angular应用程序,并且花了几天的时间试图解决这个问题,但没有任何运气。任何帮助将不胜感激。
这是我的某些节点模块的版本:
component.ts:
export class FormComponent {
@Input() loading: boolean;
@Output() update: EventEmitter<Office> = new EventEmitter<Office>();
saveForm(form: any) {
const { value, valid } = form;
if (valid) {
this.update.emit(value);
}
}
}
component.html:
<form *ngIf="!loading" (ngSubmit)="saveForm(form)" #form="ngForm" novalidate>
<mat-form-field>
<input
class="company-name"
matInput
placeholder="Company Name"
type="text"
name="companyName"
required
#companyName="ngModel"
[ngModel]="office?.companyName">
<mat-error *ngIf="companyName.errors?.required && companyName.dirty">
Company name is required
</mat-error>
</mat-form-field>
<button
class="submit-form"
mat-raised-button
type="submit"
[disabled]="form.invalid"
>
Submit
</button>
</form>
component.spec.ts:
describe('FormComponent', () => {
let component: FormComponent;
let fixture: ComponentFixture<FormComponent>;
let el: DebugElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
BrowserAnimationsModule,
FormsModule,
MatInputModule,
OverlayModule,
StoreModule.forRoot({}),
],
declarations: [FormComponent],
providers: [Actions, MatSnackBar, Store],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(FormComponent);
component = fixture.componentInstance;
el = fixture.debugElement;
component.loading = false;
fixture.detectChanges();
});
it('should submit form when submit button is clicked', () => {
// Setting input value
el.query(By.css('input.company-name')).nativeElement.value = 'Test Name';
fixture.detectChanges();
// Confirming input value changed
expect(el.query(By.css('input.company-name')).nativeElement.value).toBe(
'Test Name',
);
// Spying on update method
spyOn(component.update, 'emit').and.callThrough();
el.query(By.css('button.submit-form')).nativeElement.click();
// el.query(By.css('button.submit-form')).triggerEventHandler('click', null);
expect(component.saveForm).toHaveBeenCalled();
expect(component.update.emit).toHaveBeenCalledWith({ companyName: 'Test Name' });
}):
});
错误消息:
预期的间谍发射已由[Object({companyName: 'Test Name'})],但实际的调用是[Object({})]。