【问题标题】:Need Help to check if element is in current Viewport with Testcafe需要帮助以使用 Testcafe 检查元素是否在当前视口中
【发布时间】:2019-02-27 13:14:05
【问题描述】:

我正在尝试实现一个自定义方法来确定元素是否在当前视口中

以下是我尝试实现但结果未呈现布尔结果的代码 sn-p:

export const isElementInViewport = () => {
const getBoundValues = ClientFunction(() => document.querySelectorAll(".hero-getstart").item(0).getBoundingClientRect());

const windowHeight = ClientFunction(() => window.innerHeight);
const windowWidth = ClientFunction(() => window.innerWidth);

return getBoundValues.bottom > 0 && getBoundValues.right > 0 && getBoundValues.left < (windowWidth || document.documentElement.clientWidth) && getBoundValues.top < (windowHeight || document.documentElement.clientHeight);
};

上述代码在浏览器控制台上正常运行,即当我尝试将getBoundValues 存储在变量A 中并尝试运行return 命令时,它会根据元素的可见性将输出打印为true 或false在视口中但在脚本中,它总是给出一个错误:

这是触发上述方法的方法:

export const verifyElementInView = () => {
  const elementVisible = isElementInViewport();
  console.log(elementVisible);
};

输出总是假的。

这是我在尝试console.log(getBoundValues) 时收到的输出的 sn-p:

{ [Function: __$$clientFunction$$]
with: [Function],
[Symbol(functionBuilder)]: 
ClientFunctionBuilder {
callsiteNames: 
  { instantiation: 'ClientFunction',
    execution: '__$$clientFunction$$' },
 fn: [Function],
 options: {},
 compiledFnCode: '(function(){ return (function () {return document.querySelectorAll(".hero-getstart").item(0).getBoundingClientRect();});})();',
 replicator: 
  { transforms: [Array],
    transformsMap: [Object],
    serializer: [Object] } } }

我错过了什么?

【问题讨论】:

    标签: automated-tests viewport e2e-testing ui-testing testcafe


    【解决方案1】:

    无需为每个客户端调用创建客户端函数。相反,您可以将整个函数包装到 ClientFunction 调用中,如下所示:

    const isElementInViewport = ClientFunction(() => {
      const getBoundValues = document.querySelector("#developer-name").getBoundingClientRect();
    
      const windowHeight =  window.innerHeight;
      const windowWidth = window.innerWidth;
    
      return getBoundValues.bottom > 0 && getBoundValues.right > 0 && getBoundValues.left < (windowWidth || document.documentElement.clientWidth) && getBoundValues.top < (windowHeight || document.documentElement.clientHeight);
    });
    

    我建议您按如下方式调用您的客户端函数(如Executing Client Functions 主题中所述):

    test('ClientFunctionCall', async t => {
      const elementVisible = await isElementInViewport();
      console.log(elementVisible)
    });
    

    以下示例也可能有用:Complex DOM Queries

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 2022-12-09
      • 1970-01-01
      • 2011-05-27
      • 2019-11-23
      • 1970-01-01
      相关资源
      最近更新 更多