You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular测试:如何用Selenium Protractor测试不可编辑字段?

测试不可编辑字段的正确方案

你的现有代码只做了输入尝试,但没验证输入是否真的无效,也没检查字段本身的不可编辑属性。下面是几种靠谱的测试方式:

1. 检查字段的disabled或readonly属性

不可编辑的输入框通常会带有disabled或readonly属性,这是最直接的验证方式:

it('should verify the field is non-editable', () => {
    login('amazonuser');
    click(by.xpath('//mat-option[5]/span[contains(., "Amazon Id")]'));
    
    const amazonIdField = getElement(by.xpath('//id-number/div/mat-form-field[2]/div/div[1]/div/input'));
    
    // 检查字段是否被禁用
    expect(amazonIdField.getAttribute('disabled')).toBeTruthy();
    // 或者检查是否为只读状态
    expect(amazonIdField.getAttribute('readonly')).toBeTruthy();
    
    logout();
});

2. 尝试输入后验证内容未变化

如果字段没有明确的不可编辑属性,但实际无法输入内容,可以通过对比输入前后的值来验证:

it('should not allow editing the field', () => {
    login('amazonuser');
    click(by.xpath('//mat-option[5]/span[contains(., "Amazon Id")]'));
    
    const amazonIdField = getElement(by.xpath('//id-number/div/mat-form-field[2]/div/div[1]/div/input'));
    // 获取字段初始值
    const originalValue = amazonIdField.getAttribute('value');
    
    // 尝试输入内容
    amazonIdField.sendKeys('0');
    
    // 验证输入后值没有发生变化
    expect(amazonIdField.getAttribute('value')).toEqual(originalValue);
    
    logout();
});

3. 验证字段无法获得焦点(可选)

部分不可编辑字段会被设置为无法获取焦点,可以通过检查焦点元素来验证:

it('should not let the field gain focus', () => {
    login('amazonuser');
    click(by.xpath('//mat-option[5]/span[contains(., "Amazon Id")]'));
    
    const amazonIdField = getElement(by.xpath('//id-number/div/mat-form-field[2]/div/div[1]/div/input'));
    amazonIdField.click();
    
    // 检查当前焦点元素不是目标字段
    const activeElement = browser.driver.switchTo().activeElement();
    expect(activeElement.getAttribute('xpath')).not.toEqual(amazonIdField.locator().value);
    
    logout();
});

额外提示

如果是Angular Material的表单组件,还可以检查组件对应的ng-disabled状态,或者通过Angular的测试工具直接验证表单控件的disabled属性。

内容的提问来源于stack exchange,提问作者Hiyanneri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 11:33:15