Nightwatchjs 3.4.1多元素href与对应font-weight测试问题求助
问题根源
你之前的嵌套循环问题出在同步forEach循环里嵌套异步命令,且内部重复查询了所有目标元素,导致每次获取单个元素的href后,都会遍历输出所有元素的font-weight,无法建立一对一的对应关系。Nightwatch的命令大多是异步的,同步循环会打乱执行顺序,造成数据串位。
解决方案(Nightwatch 3.4.1适配)
以下两种方案都能保证每个链接的href与对应font-weight准确关联,完成断言验证:
方案1:使用Promise.all并行处理(推荐)
利用Nightwatch 3+支持的元素数组API,结合Promise.all批量处理每个元素的属性获取与断言:
module.exports = { '验证链接样式与href关联': function(browser) { browser .url('你的测试页面URL') .waitForElementVisible('div.review__main-content__section') .findElements('css selector', 'div.review__main-content__section a[href]') .then(elements => { return Promise.all(elements.map(element => { return Promise.all([ element.getAttribute('href'), element.getCssProperty('font-weight') ]).then(([href, fontWeightData]) => { const fontWeight = parseInt(fontWeightData.value, 10); // 按规则断言 href.includes('#') ? browser.assert.equal(fontWeight, 400, `${href} 的font-weight应为400`) : browser.assert.equal(fontWeight, 700, `${href} 的font-weight应为700`); }); })); }) .end(); } };
方案2:使用async/await顺序处理(更易读)
Nightwatch 3支持async/await语法,用for...of循环替代forEach,保证每个元素的操作顺序执行:
module.exports = { '验证链接样式与href关联': async function(browser) { await browser.url('你的测试页面URL'); await browser.waitForElementVisible('div.review__main-content__section'); const elements = await browser.findElements('css selector', 'div.review__main-content__section a[href]'); for (const element of elements) { const href = await element.getAttribute('href'); const fontWeightData = await element.getCssProperty('font-weight'); const fontWeight = parseInt(fontWeightData.value, 10); if (href.includes('#')) { await browser.assert.equal(fontWeight, 400, `${href} 的font-weight应为400`); } else { await browser.assert.equal(fontWeight, 700, `${href} 的font-weight应为700`); } } await browser.end(); } };
关键注意点
- 不要重复查询元素列表:针对单个元素直接调用
getAttribute和getCssProperty,不要在内部再次查询所有a元素。 - 异步操作要保持顺序:forEach不支持async/await的顺序执行,改用
for...of或Promise.all来保证每个元素的属性对应正确。 - font-weight值转换:
getCssProperty返回的是对象,需提取value并转为整数再断言(避免字符串格式的"400"或"normal"等情况)。
内容的提问来源于stack exchange,提问作者Darren Harley
相关产品推荐
相关产品推荐

