I'm trying to write a basic test for an Angular 2 web app which is attempting to check if my submit()
function is being called when the submit button is clicked.
When I do this it works fine both in manual testing and with my Jasmine test...
<form #addPersonForm="ngForm">
...
<button class="add-button" type="submit" (click)="submit()" tabindex="5">Add Person</button>
</form>
But when I use ngSubmit instead, the manual testing works fine but the Jasmine unit test fails (it says the submit function is never called)...
<form (ngSubmit)="submit()" #addPersonForm="ngForm">
...
<button class="add-button" type="submit" tabindex="5">Add Person</button>
</form>
(By the way, my reason for trying to get this ngSubmit method to work is that it plays along much better for validation and supporting the enter key.)
Here's what I'm doing with my Jasmine test...
it('should call the submit method', () => {
let debugElement = _fixture.debugElement;
let button = debugElement.query(By.css('.add-button'));
_fixture.detectChanges();
TestHelper.click(button);
expect(submitSpy).toHaveBeenCalled();
});
Is there something specific I need to spy on that I'm missing? I haven't found anything related to this issue in the documentation.
UPDATE
This is my click method...
/** Simulate element click. Defaults to mouse left-button click event. */
export function click(el: DebugElement | HTMLElement, eventObj: any = ButtonClickEvents.left): void {
if (el instanceof HTMLElement) {
el.click();
} else {
(<DebugElement> el).triggerEventHandler('click', eventObj);
}
}
button.nativeElement.click()
. That's what I used and it worked – Akenesubmit
event. So I just rolled with that. It doesn't test the functionality of the button click, but I just settled – Akene$(document.body).append(element)
, whereelement
is the form usingng-submit
. It seems like jQuery doesn't like submitting detached forms in newer versions of Chrome. – Knp