Test Functions Depending on a Browser API

Learn how to test functions depending on the browser’s canvas API.

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 element passed as the function parameter.

  • const context = canvas.getContext('2d');

    The line calls the getContext method of the canvas. This returns the context object that, in turn, lets us draw shapes and lines in the canvas.

  • context.rect(0, 0, width, width);

    The line uses rect to draw a rectangle in the top-right corner of the canvas, (0,0), using width as its width and height.

Run it

Let’s run the code below, look at the results, and break down the test.

Get hands-on with 1200+ tech skills courses.