Angular无法读取null DOM单元测试的属性“nativeElement”
我有一个带有多个输入字段和文本区域的表单,当键盘上发生输入键事件时,需要评估文本区域是否为空?如果为空,则在html mat错误标记上显示错误。我想为这个场景编写单元测试用例。我可以在浏览器控制台中使用jquery获取dom值,但在spec文件中无法获取dom内容 spec.ts文件Angular无法读取null DOM单元测试的属性“nativeElement”,angular,jasmine,Angular,Jasmine,我有一个带有多个输入字段和文本区域的表单,当键盘上发生输入键事件时,需要评估文本区域是否为空?如果为空,则在html mat错误标记上显示错误。我想为这个场景编写单元测试用例。我可以在浏览器控制台中使用jquery获取dom值,但在spec文件中无法获取dom内容 spec.ts文件 it('should be display warning message', () => { const textArea: HTMLTextAreaElement = fixt
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');
});
按预期获取输出:输入的信息格式无效
收到:未定义
输入textArea.value=asd~reg表达式错误
textArea.value=asd是有效的输入
下面是单元测试的示例代码。请注意,文本区域和显示元素都应该有一个id,我选择了text\u area\u 1和name\u display,这使得使用By.css查询它们更容易
很抱歉,我的组件没有isFormValid。我更新了我的问题,请仔细研究。@Rijo:我相应地修改了答案中的代码。谢谢你的回答!,在这里,我发现一个错误的名称显示此选择器将在某个时间后出现,它并不总是出现在DOM树中。因为测试执行将在DOM准备就绪之前完成。因此,如何为执行提供一些延迟不需要id,但是如果需要id,您最好使用.id'the-id'来选择它。
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');
});