Dato il seguente codice provo a testare il gancio ngOnChanges
ciclo di vita dei Angular2:test ngOnChanges gancio del ciclo di vita in angolare 2
import {
it,
inject,
fdescribe,
beforeEachProviders,
} from '@angular/core/testing';
import {TestComponentBuilder} from '@angular/compiler/testing';
import {Component, OnChanges, Input} from '@angular/core';
@Component({
selector: 'test',
template: `<p>{{value}}</p>`,
})
export class TestComponent implements OnChanges {
@Input() value: string;
ngOnChanges(changes: {}): any {
// should be called
}
}
fdescribe('TestComponent',() => {
let tcb: TestComponentBuilder;
beforeEachProviders(() => [
TestComponentBuilder,
TestComponent,
]);
beforeEach(inject([TestComponentBuilder], _tcb => {
tcb = _tcb;
}));
it('should call ngOnChanges', done => {
tcb.createAsync(TestComponent).then(fixture => {
let testComponent: TestComponent = fixture.componentInstance;
spyOn(testComponent, 'ngOnChanges').and.callThrough();
testComponent.value = 'Test';
fixture.detectChanges();
expect(testComponent.ngOnChanges).toHaveBeenCalled();
done();
}).catch(e => done.fail(e));
});
});
Purtroppo la prova non riesce con il messaggio Expected spy ngOnChanges to have been called.
so che ho potuto solo controllare il contenuto della l'elemento HTML in questo esempio, ma ho un codice che deve essere testato all'interno dell'hook del ciclo di vita di ngOnChanes, quindi questa non è una soluzione per me. Inoltre, non voglio chiamare direttamente il numero testComponent.ngOnChanges({someMockData});
nel test.
Come è possibile impostare TestComponent.value
da un test in modo da chiamare ngOnChanges
?
I don Pensa che dovresti fare un test angolare, il suo team angolare. hai solo bisogno di trovare qualsiasi motivo per testare i tuoi codici commerciali diversi dal framework stesso. –
Voglio testare il mio codice aziendale che si trova all'interno della funzione 'ngOnChanges' – user1448982
se è necessario eseguire test di e2e, forse' http: // www.protractortest.org' aiuta –