Inspired by Robert O'Callahan's blog
To reduce the need for "visual confirmation" tests:
- store the base-64 encoded data-uri of a reference png as a string
- copy the outerHTML of your test fixture into an SVG wrapper, prefixed with "data:image/svg+xml,"
- set the src of an image to the value of the SVG wrapper
- copy the image into a canvas context
- assert equality of canvas.context.toDataURL() and previously stored reference string
<!-- Copy this to into the svg-->
<div id="cssboxsizing"></div>
<!-- Copy svg to img into this-->
<canvas id="canvas-cssboxsizing" width="10" height="10"></canvas>
(function() {
var img, svg, width, height,
style = [
"-webkit-box-sizing: border-box;",
"-moz-box-sizing: border-box;",
"-ms-box-sizing: border-box;",
"-o-box-sizing: border-box;",
"box-sizing: border-box;",
"background: white;",
"border-left: 10px solid blue;",
"display: inline-block;",
"height: 10px;",
"width: 10px;"
].join(""),
reference = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAE0lEQVQYlWNgYPj/nzg8qpCuCgHLfMc5xIwHOgAAAABJRU5ErkJggg==",
fixture = document.getElementById("cssboxsizing"),
canvas = document.getElementById("canvas-cssboxsizing"),
context = canvas.getContext("2d");
fixture.setAttribute( "style", style );
width = fixture.style.width;
height = fixture.style.height;
svg = [
"data:image/svg+xml,",
"<svg xmlns='http://www.w3.org/2000/svg' width='" + width + "' height='" + height + "'>",
"<foreignObject width='" + width + "' height='" + height + "' style='line-height:" + height + "'>",
"<div xmlns='http://www.w3.org/1999/xhtml' style='width:" + width + ";height:" + height + ";padding:0px;margin:0px'>",
fixture.outerHTML,
"</div>",
"</foreignObject>",
"</svg>"
].join("");
img = new Image();
img.src = svg;
document.body.appendChild(img);
img.onload = function() {
context.createImageData( canvas.width, canvas.height );
context.drawImage( img, 0, 0 );
// https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas
// Warning: The canvas is not in fact origin clean at this time in either
// Firefox or Chrome; in Firefox, this is due to bug 672013 . In Chrome, this is due
// to a general WebKit bug that causes documents loaded from object URLs and data:
// URIs incorrectly having a different origin from their containing documents.
// WORKS!! In Firefox 11+
// console.log( context.getImageData( 0, 0, 10, 10 ) );
console.log(
context.canvas.toDataURL() === reference ? "PASS" : "FAIL"
);
};
})();