Отсутствует информация о локали для Kendo Intl Service при тестировании с Jest в Angular 7 - PullRequest
7 голосов
/ 07 мая 2019

У меня было несколько тестов для очень специфического числового компонента, который обрабатывает форматирование локали. Тесты были в порядке с Кармой, но как только мы изменили его на Jest, эта ошибка начала появляться:

NoLocale: Missing locale info for 'de-DE' Solution: http://www.telerik.com/kendo-angular-ui/components/internationalization/troubleshooting/#toc-no-locale

Я перепробовал все предложения из прикрепленных ссылок, но безуспешно.

IntlService инициализируется с en-US идентификатором локали, поэтому я менял его для каждого теста, в зависимости от формата, который я хотел утверждать (de-DE или en-GB).

Это тестовые примеры в component.spec.ts:

Числовые-textbox.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NumericTextBoxComponent } from './numeric-textbox.component';
import { FormsModule } from '@angular/forms';
import { CldrIntlService, IntlModule, load } from '@progress/kendo-angular-intl';

describe('NumericTextBoxComponent', () => {
  let component: NumericTextBoxComponent;
  let fixture: ComponentFixture<NumericTextBoxComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule, IntlModule ],
      declarations: [ NumericTextBoxComponent ],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(NumericTextBoxComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('User writes valid numbers with German/International notation', () => {
    component.format = 'n2';
    (<CldrIntlService>component.intlService).localeId = 'de-DE';
    fixture.detectChanges();
      const displayValueInput: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('input');

  // absolute integer
  displayValueInput.value = '123456789';
  displayValueInput.dispatchEvent(new Event('input'));
  displayValueInput.dispatchEvent(new Event('focusout'));
  expect(component.inputValue).toBe('123456789');
  expect(component.displayValue).toBe('123.456.789,00');
});

it('displays the correct format when the control is created in english context', () => {
    component.format = 'n2';
    (<CldrIntlService>component.intlService).localeId = 'en-GB';
    fixture.detectChanges();
      const displayValueInput: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('input');
      displayValueInput.value = '123456789.12';
      displayValueInput.dispatchEvent(new Event('input'));
      displayValueInput.dispatchEvent(new Event('focusout'));
      expect(component.inputValue).toBe('123456789.12');
      expect(component.displayValue).toBe('123,456,789.12');
  });

Редко, когда локаль 'en-GB' распознается службой Intl (поэтому тест выполняется нормально), а 'de-DE' - нет.

Мой вопрос: как импортировать информацию о локали de-DE в тестовую среду, чтобы она могла динамически распознаваться службой Intl?

ОБНОВЛЕНИЕ 10 мая 1919

* * * * * * * * * fixture.whenStable().then(()=> {}) вызывал проблему при обработке тестовой ошибки, поэтому он был удален.


В качестве дополнительной информации событие focusout вызывает следующий метод в компоненте:

Числовые-textbox.component.ts

onFocusOut(first: boolean = false): void {
      console.log("onFocusOut");
        if (this.isReadOnly && !first && !this.isFocusIn) { return; }
        this.isFocusIn = false;
        // save the temporal the editable display value into the inputValue.
        // if the escape key was pressed, then we undo the actual displayValue to the lastInputValue.
        this.inputValue = !this.wasEscapePressed ? this.displayValue : this.lastInputValue;
        this.wasEscapePressed = false;
        // update the readable display value with the absolute value of the input value (or zero if it is null, zero or empty).
        this.displayValue = this.formatDisplayValue(this.inputValue);
    }

formatDisplayValue(input: string): string {
        // single signs, nulls, empty and zeros are shown as zero
        if (this.checkNullZeroOrEmpty(input) || this.isSignOnly(input)) {
            input = NumericTextBoxComponent.ZERO;
        } else if (this.IsPositiveValue(input) && input[0] === NumericTextBoxComponent.PLUS_SIGN) {
            // positive signs at the beginning are trim
            input = input.replace(NumericTextBoxComponent.PLUS_SIGN, '');
        }

        // display value are always the absolute value
        const numberValue = Math.abs(this.getNumberValue(input));

        // finally return the number formatted based in the locale. 
        return this.intlService.formatNumber(numberValue, this.format);
    }

Итак, когда я сфокусировался на входном элементе HTML, отображаемое значение форматируется в зависимости от локали.

1 Ответ

0 голосов
/ 10 мая 2019

Я предлагаю вам попытаться импортировать его, как описано в документации, на которую вы ссылались в главе загрузка дополнительных данных локали . Поскольку вы не упоминаете, что загружаете дополнительные локали, я предполагаю, что вы вообще этого не делаете. В противном случае предоставьте дополнительную информацию о том, как вы их загружаете.

Для локали вам нужно добавить следующий импорт.

// Load all required data for the de locale
import '@progress/kendo-angular-intl/locales/de/all';
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...