【发布时间】: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" 是一个有效的输入
【问题讨论】: