需要帮助以使用Testcafe检查元素是否在当前视口中

Kis*_*uri 5 automated-tests ui-testing viewport e2e-testing testcafe

我正在尝试实现一个自定义方法,以查找元素是否在当前视图端口中

以下是我尝试实现的代码片段,但结果未呈现布尔结果:

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);
};
Run Code Online (Sandbox Code Playgroud)

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

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

export const verifyElementInView = () => {
  const elementVisible = isElementInViewport();
  console.log(elementVisible);
};
Run Code Online (Sandbox Code Playgroud)

输出始终为假。

这是我尝试执行时收到的输出摘要console.log(getBoundValues)

{ [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] } } }
Run Code Online (Sandbox Code Playgroud)

我想念什么?

Ale*_*kin 3

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

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

我建议您按如下方式调用客户端函数(如执行客户端函数中所述)主题中所述):\n\xc2\xa0

\n\n
test(\'ClientFunctionCall\', async t => {\n  const elementVisible = await isElementInViewport();\n  console.log(elementVisible)\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

\xc2\xa0\n以下示例也可能有用:复杂 DOM 查询

\n