下面的代码所做的是,当鼠标悬停在一个getBoundingClientRect标签上时,它会创建一个具有特定尺寸和位置的跨度(由<a>提供),这很好。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ollow Along Nav</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<nav>
<ul class="menu">
<li><a href="">Home</a></li>
</ul>
</nav>
<div class="wrapper">
<p>Lorem ipsum dolor sit amet, <a href="">consectetur</a> adipisicing elit. Est <a href="">explicabo</a> unde natus necessitatibus esse obcaecati distinctio, aut itaque, qui vitae!</p>
<p>Aspernatur sapiente quae sint <a href="">soluta</a> modi, atque praesentium laborum pariatur earum <a href="">quaerat</a> cupiditate consequuntur facilis ullam dignissimos, aperiam quam veniam.</p>
</div>
<script>
const triggers = document.querySelectorAll('a');
const highlight = document.createElement('span');
highlight.classList.add('highlight');
document.body.appendChild(highlight);
function highlightLink(a) {
const linkCoords = a.getBoundingClientRect();
const coords = {
width: linkCoords.width,
height: linkCoords.height,
top: linkCoords.top + window.scrollY,
left: linkCoords.left + window.scrollX
};
highlight.style.width = `${coords.width}px`;
highlight.style.height = `${coords.height}px`;
highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;
}
triggers.forEach(a => highlightLink(a));
</script>
</body>
</html>我想在脚本标记中为上面的代码创建一个单元测试,所以我想出了一个基于NodeJS的脚本
const index = require('./index.js');
//runs the html in express app
var jsdom = require('jsdom');
const { JSDOM } = jsdom;
const { document } = (new JSDOM('')).window;
global.document = document;
const test =async()=>{
const request = require('supertest');
const response = await request(index).get("/");
document.body.innerHTML = response.text;
const triggers = document.querySelectorAll('a')
var highlight = document.createElement('span');
highlight.classList.add('highlight');
document.body.appendChild(highlight);
function checkThis(a) {
const linkCoords = a.getBoundingClientRect();
console.log(linkCoords.width)
}
triggers.forEach(a => checkThis(a));
}
test()出于某种原因,对于所有的<a>标记,我的宽度都是零。甚至getBoundingClientRect中的其他属性也为零。可能的原因是什么?使用Jest和Supertest测试这段代码的最佳方法是什么?
发布于 2021-12-09 13:56:53
确保DOM准备好了。在绑定事件或访问元素之前。此外,如果要访问的元素有display:none,则始终会得到零。
要检查问题是否是DOM加载得太晚,只需记录触发器变量并查看它是否具有正确的值,如果没有,您可以这样做:
document.addEventListener('DOMContentLoaded', (event) => {
// put code that needs to wait for DOM to load here
})https://stackoverflow.com/questions/70290905
复制相似问题