Angular не может прочитать свойство 'nativeElement' в модульном тестировании с нулевым DOM - PullRequest
0 голосов
/ 23 января 2020

У меня есть форма с номером поля ввода и текстовой области, когда происходит событие клавиатуры (ввода) в текстовой области, нужно оценить, текстовая область пуста или нет? Если это пустая ошибка, отображается в теге html mat-error. Я хотел бы написать пример модульного теста для этого сценария. Я могу получить значение dom, используя jquery в консоли браузера, но в файле spe c не могу получить содержимое DOM.

spe c .ts file

    it('should be display warning message', () => {
          const textArea: HTMLTextAreaElement = fixture.debugElement.query(By.css('.need-access-shipping-address textarea')).nativeElement as HTMLTextAreaElement;
          textArea.value = "asd`";
          const event = new KeyboardEvent("keypress",{
            "key": "Enter"
          });
          textArea.dispatchEvent(event);
          fixture.detectChanges();
          const nameDisplay: HTMLElement = fixture.debugElement.query(By.css('.need-access-shipping-address .mat-error')).nativeElement as HTMLElement;
          expect(nameDisplay.innerText).toBe('The format of the information entered is invalid');
    });

вывод получен как Expected: "The format of the information entered is invalid" Received: undefined

Ввод textArea.value = "asd~" ошибка выражения reg

textArea.value = "asd" является допустимым вводом

enter image description here

1 Ответ

1 голос
/ 23 января 2020

Вот пример кода модульного теста. Обратите внимание, что text-area и элемент дисплея должны иметь id (я выбрал text_area_1 и name_display), что облегчает их запрос с помощью By.css.

it('pressing <enter> in empty text area should invalidate form', () => {

    // given
    const htmlTextArea: HTMLTextAreaElement = fixture.debugElement.query(By.css('#text_area_1')).nativeElement;
    htmlTextArea.value = 'asd~';
    htmlTextArea.dispatchEvent(new Event('input'));
    fixture.detectChanges();

    // when
    const event: any = document.createEvent('Event');
    event.key = 'Enter';
    event.initEvent('keyup');
    htmlTextArea.dispatchEvent(event);
    fixture.detectChanges();

    // then
    const nameDisplay: HTMLElement = fixture.debugElement.query(By.css('#name_display')).nativeElement;
    expect(nameDisplay.innerText).toBe('The format of the information entered is invalid');
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...