...

/

Test Functions Depending on a Browser API

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. ... ...

Access this course and 1400+ top-rated courses and projects.