Angular2 test form: submit method not called

The presence of this component

import {Component} from 'angular2/core';
import { FORM_DIRECTIVES } from 'angular2/common';

@Component({
    selector: 'something',
    templateUrl: 'something.html',
    providers: [],
    directives: [FORM_DIRECTIVES],
    pipes: []
})
export class Something {

    constructor() { }

    save(data) {
        alert(data);
    }
}

with this template (something.html)

<form #myForm="ngForm" (ngSubmit)="save(myForm.value)">
    <label for="title">Title</label>
    <input id="title" type="text" ngControl="title" />

    <label for="primaryImage">Primary Image</label>
    <input id="primaryImage" type="text" ngControl="primaryImage" />

    <button type="submit">Save</button>
</form>

and this test

it('should call save method after clicking a Save button', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    return tcb.createAsync(Something).then((fixture) => {
        spyOn(fixture.componentInstance, 'save');
        fixture.detectChanges();
        const compiled = fixture.nativeElement;
        compiled.querySelector('#title').value = 'testTitle';
        compiled.querySelector('#primaryImage').value = 'tabc.png';                   
        compiled.querySelector('button').click();
        expect(fixture.componentInstance.save).toHaveBeenCalledWith({
            title: 'testTitle',
            primaryImage: 'abc.png'
        });
    });
}));

The test fails, the save method was not called by the spy. However, when I manually try in the browser, if it works, a warning is displayed. The test also fails if instead of button.click I do form.submit.

When I use (click)="save(myForm.value)"the button instead of ngSubmitin the form, the test still fails, but the reason is different. In this case, the save method on the spire was called, but the data transferred to it {}.

Can someone tell me what I am missing here?

+2
source share
3 answers

Juanmi, , , , , , , ,

, click() ( debug). . , ReactiveForms, .

<form [formGroup]="sampleForm" (submit)="submit($event)">
    <input id="sampleBtn" type="submit" class="btn-default btn btn-primary" value="Click Me">
</form>

spec.ts

spyOn(fixture.componentInstance, 'submit');
let loginBtn: DebugElement = fixture.debugElement.query(By.css('#sampleBtn'));
loginBtn.nativeElement.click();
fixture.detectChanges();
expect(fixture.componentInstance.submit).toHaveBeenCalled();

() , , () . . :)

+5

-:

By triggerHandle

let form = fixture.debugElement.query(By.css('form'));
form.triggerEventHandler('submit', null);
fixture.detectChanges();
// your component function should have been called

, , , ngSubmit. .submit , .

+7

Try adding fixture.detectChanges();right before clicking.

+2
source

Source: https://habr.com/ru/post/1661477/


All Articles