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

使用Nightwatch.js断言元素属性值的逻辑或判断问题

问题分析与解决方法

核心错误点

  1. 赋值运算符误用:代码中用=(赋值)替代了===(严格相等比较),比如if (mpuWidth = '320')会直接把mpuWidth设为'320',条件永远为真,而非判断两者是否相等。
  2. 逻辑或运算错误:'100' || '200'的运算结果永远是'100'——逻辑或操作会返回第一个为真的表达式,非空字符串均为真,所以断言只会和'100'对比,自然无法匹配'200'。
  3. 异步操作顺序问题:原代码中两个getAttribute是异步执行的,height的回调可能在width的回调之前执行,此时mpuWidth还未被赋值,导致后续判断失效。

正确实现方式

方式1:使用Async/Await(推荐,代码更清晰)

Nightwatch 1.7版本支持async/await,可避免异步回调嵌套问题:

module.exports = {
  '验证iframe尺寸规则': async function(browser) {
    // 同步获取width和height属性值
    const { value: mpuWidth } = await browser.getAttribute('#mpu-gallery iframe', 'width');
    const { value: mpuHeight } = await browser.getAttribute('#mpu-gallery iframe', 'height');

    if (mpuWidth === '320') {
      // 使用ok断言结合数组包含判断,验证height是否为100或200
      browser.assert.ok(
        ['100', '200'].includes(mpuHeight),
        `预期height为100或200,实际得到:${mpuHeight}`
      );
    }
  }
};

方式2:嵌套回调(兼容传统写法)

如果不使用async/await,需将height的获取嵌套在width的回调中,确保执行顺序:

browser.getAttribute('#mpu-gallery iframe', 'width', function(adWidth) {
  const mpuWidth = adWidth.value;
  
  browser.getAttribute('#mpu-gallery iframe', 'height', function(adHeight) {
    const mpuHeight = adHeight.value;
    
    if (mpuWidth === '320') {
      // 自定义断言逻辑
      const isValidHeight = mpuHeight === '100' || mpuHeight === '200';
      browser.assert.ok(isValidHeight, `height值无效:${mpuHeight},需为100或200`);
    }
  });
});

针对第二次尝试代码的修正

第二次代码同样存在赋值运算符误用,且else if条件与if重复,修正后应为:

// 假设已正确获取mpuAdWidth和mpuAdHeight
if (mpuAdWidth === '300') {
  // 用数组包含判断height是否符合要求
  browser.assert.ok(['250', '600'].includes(mpuAdHeight), 
    `预期height为250或600,实际得到:${mpuAdHeight}`);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:00:21