У меня было несколько тестов для очень специфического числового компонента, который обрабатывает форматирование локали. Тесты были в порядке с Кармой, но как только мы изменили его на 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, отображаемое значение форматируется в зависимости от локали.