我们(我的团队)正在建设的设计系统,其中包括数字网页组件(如按钮,链接等)使用点燃元素。设计系统附带规范定义,在我们的文档站点上有文档记录。我们希望测试应用于web组件的CSS类属性。
我们可以使用window.getComputedStyle()进行以下部分测试:
it('test CSS class properties',()=>{
const element = document.querySelector('selector');
const styles = window.getComputedStyle(element );
const content_property = style.getPropertyValue('justify-content');
expect(content_property).toEqual('space-between');
});这里出现了一个问题,当它在浏览器中呈现时,计算样式属性与在样式表中定义的不同。例如width:100%,它变成width:1366px (容器的长度)。
现在,我们只在无头浏览器中测试一个web组件,这意味着没有CSS覆盖。
是否与浏览器使用JavaScript方法/API?计算样式的方式相同,因此我们可以提前计算CSS类属性,并将其与浏览器的计算样式属性进行比较。
丑陋的方法是从浏览器中的规范文档中创建一个具有相同类的虚拟元素,并根据原始web组件的CSS类属性检查它的CSS类属性。
如有任何建议请见谅!
发布于 2020-06-29 10:48:23
我通过比较computedStyle提供的值和车身的宽度来测试它。如果它提供相同的值,我将其更改为100%。这样就可以通过比较来解决这个问题。
const element = document.querySelector("body");
const styles = window.getComputedStyle(element);
const content_property = styles.getPropertyValue("width") == document.body.clientWidth + 'px' ? '100%' : styles.getPropertyValue("width");
console.log(styles.getPropertyValue("width"));
console.log(content_property);body {
width: 100%;
}
比方说,我们有父母和孩子。相同的方法可以确定百分比宽度。
const parent = document.querySelector(".parent");
const child = document.querySelector(".child");
const styles = window.getComputedStyle(child);
const content_property = styles.getPropertyValue("width") == document.querySelector(".parent").clientWidth * (20/100) + 'px' ? '20%' : styles.getPropertyValue("width");
console.log(styles.getPropertyValue("width"));
console.log(content_property);.parent {
position: relative;
width: 300px;
height: 300px;
background: yellow;
}
.child {
position: absolute;
width: 20%;
height: 100%;
background: pink;
}<div class="parent">
<div class="child"></div>
</div>
我也把颜色转换成十六进制。
const a = document.querySelector(".a");
const styles = window.getComputedStyle(a);
function rgbToHex(r, g, b) {
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
}
const rgbColor = JSON.stringify(styles.color);
let r = parseInt(rgbColor.slice(rgbColor.indexOf("(") + 1, rgbColor.indexOf(",")));
let g = parseInt(rgbColor.slice(rgbColor.indexOf(",") + 1, rgbColor.lastIndexOf(",")));
let b = parseInt(rgbColor.slice(rgbColor.lastIndexOf(",") + 1, rgbColor.lastIndexOf(")")));
console.log(styles.getPropertyValue("color"));
console.log(r);
console.log(g);
console.log(b);
console.log(rgbToHex(r, g, b));.a {
color: #761f8c;
}<div class="a"></div>
https://stackoverflow.com/questions/62636293
复制相似问题