How to change value of a select box in angular2 unit test?

后端 未结 4 909
渐次进展
渐次进展 2020-12-29 05:34

I have an Angular2 component that contains a select box that looks like


  

Unit test:

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)
  })
})

提交回复
热议问题