Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
Prueba de unidad de enlace bidireccional NgModel angular

Estoy intentando probar la función de enlace bidireccional en Angular 2. También he leído algunas otras respuestas, pero todavía no puedo pasar la prueba.

Cuando se actualice el campo de entrada, me gustaría ejecutar una prueba que garantice que la propiedad searchQuery en la clase AppComponent sea el mismo que el valor del campo de entrada.

Como se mencionó, he leído algunas otras respuestas y, a medida que avanzaba, incluí piezas de código adicionales. Entonces, ¿qué hay actualmente que podría no ser necesario?

Componente

 import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: '<input type="text" name="input" [(ngModel)]="searchQuery" (change)="onChange()" id="search">', styles: [''] }) export class AppComponent { public searchQuery: string; onChange() { console.log(this.searchQuery); } }

Prueba de unidad

 import { ComponentFixture, TestBed, async, fakeAsync, tick, ComponentFixtureAutoDetect } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { DebugElement } from '@angular/core'; import { AppComponent } from './app.component'; import { FormsModule } from '@angular/forms'; describe('AppComponent', () => { let comp: AppComponent; let fixture: ComponentFixture<AppComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], providers: [], imports: [ FormsModule ], schemas: [] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AppComponent); comp = fixture.componentInstance; }); it('should create the app', fakeAsync(() => { const de = fixture.debugElement.query(By.css("#search")); const el = de.nativeElement; el.value = "My string"; var event = new Event('input', { 'bubbles': true, 'cancelable': true }); el.dispatchEvent(event); tick(); fixture.detectChanges(); expect(comp.searchQuery).toEqual("My string"); })); });

Si hay un mejor enfoque, por supuesto, estoy feliz de recibir comentarios al respecto.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

tienes que correr

 fixture.detectChanges();

antes de enviar el evento para asegurarse de que su control se haya inicializado y registrado en el evento onChange

función setUpControl

 // view -> model dir.valueAccessor.registerOnChange(function (newValue) { dir.viewToModelUpdate(newValue); control.markAsDirty(); control.setValue(newValue, { emitModelToViewChange: false }); });

Ejemplo de Plunker

Ver también

  • Angular2 NgModel no obtiene valor en la prueba Jasmine
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!