Test Functions Depending on a Browser API
Learn how to test functions depending on the browser’s canvas API.
We'll cover the following...
The function
While working on browser applications, we often need to use APIs the browser provides, like document.createElement. How do we go about testing such functions? Let’s use a function that draws a square as an example.
Here’s the breakdown of src/draw-square.mjs as seen in the code playground below:
-
export function drawSquare(element, width) {We export the function for other modules to import and use. The function expects element and width parameters.
-
const canvas = document.createElement('canvas');The line creates a canvas HTML element,
<canvas></canvas>, using the browser API.
Note: It’s not attached to the DOM yet.
-
element.appendChild(canvas);The line attaches the canvas element to the DOM by appending it to the
elementpassed as the function parameter. -
const context = canvas.getContext('2d');The line calls the
getContextmethod of the canvas. This returns thecontextobject that, in turn, lets us draw shapes and lines in the canvas. ... -
context.rect(0, 0, width,