【问题标题】:Angular cannot read property 'nativeElement' of null DOM unit testingAngular 无法读取空 DOM 单元测试的属性“nativeElement”
【发布时间】:2020-05-09 08:25:15
【问题描述】:

我有一个带有多个输入字段和文本区域的表单,当文本区域上发生键盘(输入)键事件时需要评估文本区域是否为空?如果它是空的错误显示在 html mat-error 标签上。我想为这种情况编写单元测试用例。我可以在浏览器控制台中使用 jquery 获取 dom 值,但是在 spec 文件中无法获取 DOM 内容。

spec.ts 文件

    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" 是一个有效的输入

【问题讨论】:

    标签: angular jasmine


    【解决方案1】:

    这是单元测试的示例代码。请注意text-area 和显示元素都应该有一个id(我选择了text_area_1name_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');
    });
    

    【讨论】:

    • 抱歉我的组件没有isFormValid()。我更新了我的问题,请调查一下。
    • @Rijo:我相应地调整了答案中的代码。
    • 感谢您的回答!,在这里我发现了一个错误#name_display 这个选择器会在一段时间后出现,它并不总是出现在 DOM 树中。因为该测试执行将在 DOM 准备好之前完成。那么如何给执行一些延迟
    • 不需要id,但是如果你也可以使用By.id('the-id')来选择它。
    猜你喜欢
    • 2022-08-22
    • 2018-03-10
    • 1970-01-01
    • 2019-10-14
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    相关资源
    最近更新 更多