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

如何在Nightwatch测试脚本中引用命令脚本的返回值?

Nightwatch.js 自定义命令返回值调用错误问题

我在Nightwatch.js的命令脚本getImageDetails.js中编写了如下代码:

exports.command = async function() {
  const specsAltText = await this.element('.specs-search-results__head-panel__image-container img').getAttribute('alt');
}

我需要将该命令脚本中的specsAltText值引用到测试脚本testingImageDetails.js中,测试脚本代码如下:

var specsAltText = require('../getImageDetails');

describe('What is the alt text of the image', function() {
  browser.getImageDetails(specsAltText);
  console.log(specsAltText)
})

但这种方式无法正常工作,控制台输出为:

{ command: [AsyncFunction (anonymous)] }

请问我哪里操作错误了?


错误原因及修正方案

1. 自定义命令未返回目标值

你的getImageDetails.js里的异步函数仅获取了图片的alt文本,但没有将值返回,导致调用命令后无法拿到实际结果。

修改getImageDetails.js,添加返回语句:

exports.command = async function() {
  return await this.element('.specs-search-results__head-panel__image-container img').getAttribute('alt');
}

2. 测试脚本调用逻辑错误

  • 直接require命令文件得到的是整个模块对象,不是alt文本值,这就是控制台输出模块结构的原因。
  • Nightwatch自定义命令通过browser对象调用,且因为是异步操作,必须用await等待执行完成,否则只能拿到Promise对象而非实际值。

修改testingImageDetails.js:

describe('What is the alt text of the image', async function() {
  const specsAltText = await browser.getImageDetails();
  console.log(specsAltText);
})

3. 其他注意事项

  • 测试函数必须标记为async,才能在内部使用await语法。
  • 确认元素定位器.specs-search-results__head-panel__image-container img能正确找到目标图片,否则会返回空或报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 03:13:13