Próbuję przetestować składnik zawierający element wprowadzania tekstu. Chcę sprawdzić, czy stan składnika zmienia się zgodnie z oczekiwaniami, gdy zmienia się wartość wprowadzanego tekstu. Wprowadzanie tekstu oczywiście wykorzystuje dyrektywę ngModel (bindowanie dwukierunkowe).Jak wyzwalać aktualizację modelu ngModel w teście jednostki Angular 2?
Mimo że komponent działa poprawnie w środowisku wykonawczym, nie mogę utworzyć poprawnego, zaliczającego testu. Opublikowalem to, co moim zdaniem powinno dzialac ponizej, a wynik testu nastepuje po tym.
Co robię źle?
TEST:
import {Component} from 'angular2/core';
import {describe, it, injectAsync, TestComponentBuilder} from 'angular2/testing';
import {FORM_DIRECTIVES} from 'angular2/common';
import {By} from 'angular2/platform/common_dom';
class TestComponent {
static get annotations() {
return [
new Component({
template: '<input type="text" [(ngModel)]="name" /><p>Hello {{name}}</p>',
directives: [FORM_DIRECTIVES]
})
]
}
}
describe('NgModel',() => {
it('should update the model', injectAsync([TestComponentBuilder], tcb => {
return tcb
.createAsync(TestComponent)
.then(fixture => {
fixture.nativeElement.querySelector('input').value = 'John';
const inputElement = fixture.debugElement.query(By.css('input'));
inputElement.triggerEventHandler('input', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(fixture.componentInstance.name).toEqual('John');
});
}));
});
WYJŚCIE:
Chrome 45.0.2454 (Mac OS X 10.10.5) NgModel should update the model FAILED
Expected undefined to equal 'John'.
at /Users/nsaunders/Projects/ng2-esnext-seed/src/test/ngmodel.spec.js!transpiled:41:52
at ZoneDelegate.invoke (/Users/nsaunders/Projects/ng2-esnext-seed/node_modules/angular2/bundles/angular2-polyfills.js:322:29)
at Zone.run (/Users/nsaunders/Projects/ng2-esnext-seed/node_modules/angular2/bundles/angular2-polyfills.js:218:44)
at /Users/nsaunders/Projects/ng2-esnext-seed/node_modules/angular2/bundles/angular2-polyfills.js:567:58
at ZoneDelegate.invokeTask (/Users/nsaunders/Projects/ng2-esnext-seed/node_modules/angular2/bundles/angular2-polyfills.js:355:38)
at Zone.runTask (/Users/nsaunders/Projects/ng2-esnext-seed/node_modules/angular2/bundles/angular2-polyfills.js:254:48)
at drainMicroTaskQueue (/Users/nsaunders/Projects/ng2-esnext-seed/node_modules/angular2/bundles/angular2-polyfills.js:473:36)
at XMLHttpRequest.ZoneTask.invoke (/Users/nsaunders/Projects/ng2-esnext-seed/node_modules/angular2/bundles/angular2-polyfills.js:425:22)
Co powiesz na czytanie [kodu źródłowego] (https://github.com/angular/angular/blob/f9fb72fb0e9bcbda7aeebbf8321ce5d70d78ecee/modules/angular2/test/common/forms/integration_spec.ts#L824)? –
Dzięki, najwyraźniej przeoczyłem to podczas wyszukiwania źródła dla odpowiedniego przykładu. Szkoda, że w tym przykładzie użyto czegoś, co wydaje się być prywatnym API (dispatchEvent from angular2/testing_internal), ale dałem mi pomysł wypróbowania przynajmniej fakeAsync. –