typescript 如何在angular2单元测试中更改选择框的值?

yhxst69z  于 2022-12-14  发布在  TypeScript
关注(0)|答案(4)|浏览(168)

我有一个Angular2组件,其中包含一个如下所示的选择框

<select [(ngModel)]="envFilter" class="form-control" name="envSelector" (ngModelChange)="onChangeFilter($event)">
    <option *ngFor="let env of envs" [ngValue]="env">{{env}}</option>
</select>

我正在尝试为ngModelChange事件编写单元测试。这是我最近一次失败的尝试

it("should filter and show correct items", async(() => {
    fixture.detectChanges();
    fixture.whenStable().then(() => {
        el = fixture.debugElement.query(By.name("envSelector"));
        fixture.detectChanges();
        makeResponse([hist2, longhist]);
        comp.envFilter = 'env3';
        el.triggerEventHandler('change', {});
        fixture.whenStable().then(() => {
            fixture.detectChanges();
            expect(comp.displayedHistory).toEqual(longhist);
        });
    });

我遇到的问题是,更改底层模型comp.envFilter = 'env3';的值不会触发change方法。我添加了el.triggerEventHandler('change', {});,但这会抛出Failed: Uncaught (in promise): ReferenceError: By is not defined。我在文档中找不到任何提示......有什么想法吗?

7kqas0il

7kqas0il1#

就错误而言。看起来你只需要导入By。这不是全局的东西。它应该从下面的模块导入

import { By } from '@angular/platform-browser';

至于测试部分,这是我已经能够弄清楚的。当你改变组件中的一个值时,你需要触发一个变化检测来更新视图。你可以用fixture.detectChanges()来做这件事。一旦完成了这件事,* 通常 * 视图应该用这个值来更新。
通过测试类似于您的示例的东西,似乎情况并非如此。似乎在变更检测之后仍有一些异步任务在进行。

const comp = fixture.componentInstance;
const select = fixture.debugElement.query(By.css('select'));

comp.selectedValue = 'a value';
fixture.DetectChanges();
expect(select.nativeElement.value).toEqual('1: a value');

这似乎不起作用。似乎有一些异步正在进行,导致值还没有设置。所以我们需要通过调用fixture.whenStable等待异步任务

comp.selectedValue = 'a value';
fixture.DetectChanges();
fixture.whenStable().then(() => {
  expect(select.nativeElement.value).toEqual('1: a value');
});

上面的方法是可行的,但是现在我们需要触发change事件,因为它不会自动发生。

fixture.whenStable().then(() => {
  expect(select.nativeElement.value).toEqual('1: a value');

  dispatchEvent(select.nativeElement, 'change');
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    // component expectations here
  });
});

现在我们有了另一个来自事件的异步任务。
下面是我测试的一个完整的测试。它是对source code integration tests示例的重构。他们使用了fakeAsynctick,这与使用asyncwhenStable类似。但是对于fakeAsync,你不能使用templateUrl,所以我认为最好重构为使用async
源代码测试也做了双重单向测试,首先测试模型到视图,然后测试视图到模型。虽然看起来你的测试是尝试做一种双向测试,从模型到模型。所以我重构了一点,以更好地适合你的例子。

import { Component } from '@angular/core';
import { TestBed, getTestBed, async } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { dispatchEvent } from '@angular/platform-browser/testing/browser_util';

@Component({
  selector: 'ng-model-select-form',
  template: `
    <select [(ngModel)]="selectedCity" (ngModelChange)="onSelected($event)">
      <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option>
    </select>
  `
})
class NgModelSelectForm {
  selectedCity: {[k: string]: string} = {};
  cities: any[] = [];

  onSelected(value) {
  }
}

describe('component: NgModelSelectForm', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule ],
      declarations: [ NgModelSelectForm ]
    });
  });

  it('should go from model to change event', async(() => {
    const fixture = TestBed.createComponent(NgModelSelectForm);
    const comp = fixture.componentInstance;
    spyOn(comp, 'onSelected');
    comp.cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}];
    comp.selectedCity = comp.cities[1];
    fixture.detectChanges();
    const select = fixture.debugElement.query(By.css('select'));

    fixture.whenStable().then(() => {
      dispatchEvent(select.nativeElement, 'change');
      fixture.detectChanges();
      fixture.whenStable().then(() => {
        expect(comp.onSelected).toHaveBeenCalledWith({name : 'NYC'});
        console.log('after expect NYC');
      });
    });
  }));
});
wsewodh2

wsewodh22#

我发现peeskillet的答案非常有用,但遗憾的是,它有点过时了,因为调度事件的方式已经改变了。我还发现有一个不必要的调用whenStable()。所以这里是一个使用peeskillet的设置更新的测试:

it('should go from model to change event', async(() => {
        const fixture = TestBed.createComponent(NgModelSelectForm);
        const comp = fixture.componentInstance;
        spyOn(comp, 'onSelected');
        comp.cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}];
        comp.selectedCity = comp.cities[1];
        fixture.detectChanges();
        const select = fixture.debugElement.query(By.css('select'));

        fixture.whenStable().then(() => {
            select.nativeElement.dispatchEvent(new Event('change'));
            fixture.detectChanges();
            expect(comp.onSelected).toHaveBeenCalledWith({name : 'NYC'});
            console.log('after expect NYC');
        });
    }));
disho6za

disho6za3#

看这个例子,来自Angular 源(template_integration_spec.ts)

@Component({
  selector: 'ng-model-select-form',
  template: `
    <select [(ngModel)]="selectedCity">
      <option *ngFor="let c of cities" [ngValue]="c"> {{c.name}} </option>
    </select>
  `
})
class NgModelSelectForm {
  selectedCity: {[k: string]: string} = {};
  cities: any[] = [];
}


  it('with option values that are objects', fakeAsync(() => {
       const fixture = TestBed.createComponent(NgModelSelectForm);
       const comp = fixture.componentInstance;
       comp.cities = [{'name': 'SF'}, {'name': 'NYC'}, {'name': 'Buffalo'}];
       comp.selectedCity = comp.cities[1];
       fixture.detectChanges();
       tick();

       const select = fixture.debugElement.query(By.css('select'));
       const nycOption = fixture.debugElement.queryAll(By.css('option'))[1];

       // model -> view
       expect(select.nativeElement.value).toEqual('1: Object');
       expect(nycOption.nativeElement.selected).toBe(true);

       select.nativeElement.value = '2: Object';
       dispatchEvent(select.nativeElement, 'change');
       fixture.detectChanges();
       tick();

       // view -> model
       expect(comp.selectedCity['name']).toEqual('Buffalo');
     }));
svujldwt

svujldwt4#

与OP提出的问题相同,但代码略有不同。
适用于Angular 7。
于飞:

<select id="dashboard-filter" class="form-control" name="dashboard-filter" [ngModel]="dashboardFilterValue" (ngModelChange)="onFilterChange($event)"
              [disabled]="disabled">
  <option *ngFor="let filter of dashboardFilters" [ngValue]="filter.value">{{ filter.name }}</option>
</select>

单元测试:

it('onFilterChange', () => {

  // ensure dropdown is enabled
  expect(component.disabled).toBe(false)

  // spies
  spyOn(component, 'onFilterChange').and.callThrough()
  spyOn(component.filterChange, 'emit')

  // initially the 3rd item in the dropdown is selected
  const INITIAL_FILTER_INDEX = 2
  // we want to select the 5th item in the dropdown
  const FILTER_INDEX = 4
  // the expected filter value is the value of the 5th dashboard filter (as used to populate the dropdown)
  const EXPECTED_FILTER_VALUE = getDashboardFiltersData.dashboardFilters[FILTER_INDEX].value

  // handle on the dropdown
  const filterDropdown = fixture.debugElement.query(By.css('select')).nativeElement

  // let bindings complete
  fixture.whenStable().then(() => {

    // ensure filterDropdown.value is stable
    expect(filterDropdown.value).toContain(getDashboardFiltersData.dashboardFilters[INITIAL_FILTER_INDEX].value)

    // update filterDropdown.value and dispatch change event
    filterDropdown.value = filterDropdown.options[FILTER_INDEX].value
    filterDropdown.dispatchEvent(new Event('change'))

    // check component data
    expect(component.dashboardFilterValue).toBe(EXPECTED_FILTER_VALUE)
    expect(component.dashboardFilterChangeInProgress).toBe(false)

    // check spies
    expect(component.onFilterChange).toHaveBeenCalledWith(EXPECTED_FILTER_VALUE)
    expect(setDashboardFilterSpy).toHaveBeenCalledWith(EXPECTED_FILTER_VALUE)
    expect(component.filterChange.emit).toHaveBeenCalledWith(true)
  })
})

相关问题