三种Angular 测试的场景总结

108 阅读1分钟

前提

  • Angular version 14
  • Node version 18

HTML文件

// app.component.html

<div class="input-context">
  <div class="input-title">Input</div>
  <input
    placeholder="placeholder"
    (change)="onChange($event)"
  />
  <div class="input-message" *ngIf="inputValue">The input value is {{ inputValue }}</div>
</div>
<div class="form">
  <label for="name">Name: </label>
  <input id="name" type="text" [formControl]="name">
  <p>Value: {{ name.value }}</p>
  <button type="button" (click)="updateName()">Update Name</button>
</div>

JS 文件

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, NgIf, ReactiveFormsModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  inputValue = '';
  name = new FormControl('');

  onChange(event: any) {
    this.inputValue = event.target.value;
  }

  updateName() {
    this.name.setValue('N');
  }
}

1. 使用nativeElement的测试方式

// test.js 

it('should trigger input event by nativeElement', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const inputElement = fixture.nativeElement.querySelector('.input-context').querySelector('input');

    inputElement.value = 'A';
    // important
    inputElement.dispatchEvent(new Event('change'));

    fixture.detectChanges();

    const inputMsgElement = fixture.nativeElement.querySelector('.input-message');
    expect(inputMsgElement.textContent).toEqual('The input value is A')
  });

2. 使用debugElement的测试方式

// test.js 

  it('should trigger input event by debugElement', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const inputElement = fixture.debugElement.query(By.css('.input-context')).query(By.css('input'));

    // important
    inputElement.triggerEventHandler("change", { target: { value: 'A' } });
    fixture.detectChanges();

    expect(fixture.componentInstance.inputValue).toEqual('A')
  });

3. 使用FormControl.patchValue()的测试方式

// test.js 

  it('should change value by FormControl', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const nameControl = fixture.componentInstance.name;
    // important
    nameControl.patchValue('Test');

    fixture.detectChanges();

    const msgElement = fixture.nativeElement.querySelector('.form').querySelector('p');
    expect(msgElement.textContent).toEqual('Value: Test')
  });
});