0

Hi I am writing unit test case in jasmine. I am new to jasmine. I have one form in html and I am trying to write unit test case for this.

Below is my html code for form.

<form *ngIf="formResetToggle" class="form-horizontal" name="tenantEditorForm" #f="ngForm" novalidate
      (ngSubmit)="f.form.valid ? saveTenant() :
      (!tenantname.valid && showErrorAlert('Tenant name is required', 'Please enter a name for the tenant'));">

</form>

Below is the spec.

it('Save Tenant', fakeAsync(() => {
        fixture.detectChanges();
        spyOn(component, 'saveTenant');
        let submitButton = fixture.debugElement.query(By.css('#saveTenant'));
        submitButton.triggerEventHandler('click', null);
        tick();
        fixture.detectChanges();
        expect(component.saveTenant).toHaveBeenCalled();
    }));

This spec gives me error

Expected spy saveTenant to have been called.

Can someone help me to figure it out the issue? Any help would be appreciated. Thanks

1 Answer 1

1

The main problem here is caused because debugElement.triggerEventHandler methods triggers event handlers that were registered on current debugElement while you want to handle submit event on form.

In this case I would suggest you using native click event instead.

submitButton.nativeElement.click();

See also:

Plunker Example

Sign up to request clarification or add additional context in comments.

1 Comment

Check my added example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.