【问题标题】:Night watch change value of textContent or innerHTML守夜更改 textContent 或 innerHTML 的值
【发布时间】:2018-02-01 23:15:21
【问题描述】:

我有以下标记,我需要能够更改这些项目的 textContent 的值:

<div class=".react-grid-HeaderCell-sortable">Jamie</div>
<div class=".react-grid-HeaderCell-sortable">Hutber</div>
<div class=".react-grid-HeaderCell-sortable">Stackoverflow</div>

我知道如何更改输入字段的值,但目前不知道如何处理文本,也许使用自定义命令?

对于输入

  .setValue('.someSelector', 'anewString')

【问题讨论】:

  • 也许与execute 一样this answer
  • Ye HMR 我曾经考虑过执行,它肯定是一个非常现实的选项,然后在我直接在浏览器中完成后断言细节?
  • 我想是的,文档没有提到异步执行,甚至声明它假设您传递的脚本是同步的。

标签: javascript testing nightwatch.js


【解决方案1】:
 Array.from(document.getElementsByClassName('react-grid-HeaderCell-sortable'))
     .forEach(x => x.innerHTML = 'new text')

说明: document.getElementsByClassName 返回一个HTMLCollection,需要将其转换为带有Array.from 的数组才能可迭代。

要修改div 的文本,您需要设置innerHTML 属性。请注意innerHTML 可以替换为textContent,有关区别的更多信息,请参阅 W3C 文档。

【讨论】:

  • 如何在 NW 中运行它?
  • execute,正如@HMR 在评论中提到的那样
【解决方案2】:

如前所述,唯一的方法是使用 .execute() 并从页面上下文中修改 DOM。

但是,根据您的特定用例,您可能希望使用更复杂的选择器,因此我建议使用 querySelector()

此外,您还可以为此操作创建快捷方式,如下所示:

module.exports = {
  'Test': function(client) {
    client
      .url('http://some.url')
      .execute(setElementValue, ['table.selector > .child-selector', 'new value'])
      .end();
  }
};

function setElementValue(selector, value) {
  document.querySelector(selector).textContent = value;
}

您不妨为此创建一个自定义命令,这样您就可以在其他测试中重用它并使您的代码看起来不错:

// ./lib/custom-commands/setElementValue.js

exports.command = function(selector, value) {
  this.execute(function(selector, value) {
    document.querySelector(selector).textContent = value;
  }, [selector, value]);

  return this;
};

// Test case

client
  .url('http://some.url')
  .setElementValue('table.selector > .child-selector', 'new value')
  .end();

不要忘记通过设置配置文件的custom_commands_path 属性将 Nightwatch 指向您保存自定义命令的目录。

【讨论】:

    猜你喜欢
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2020-11-10
    • 2023-03-29
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多