37

How can I unit-test Javascript that draws on an HTML canvas? Drawing on the canvas should be checked.

7
  • Could you expand your question a bit? Exactly what do you want to test? You probably have to write some form of validation functions to make testing easier. Dec 10, 2010 at 9:16
  • I want to test a Javascript chart drawing engine. I want to check if the suitable lines and shapes are placed into the HTML canvas at the right places. (coordinates, color, thickness, etc.)
    – pcjuzer
    Dec 10, 2010 at 11:18
  • 3
    Ok. I guess you could whip up something via dev.w3.org/html5/2dcontext/#dom-context-2d-getimagedata . You can use that method to check out pixel's color. It might help if you could write some dummy tests just to figure out what kind of API you are going to need. Dec 10, 2010 at 14:48
  • It would be fully enough for me to check that the certain functions have been invoked with the suitable parameters on canvas. I think about some kind of proxy.
    – pcjuzer
    Apr 26, 2011 at 10:08
  • 3
    A canvas testing utility: github.com/HumbleSoftware/js-imagediff
    – pcjuzer
    Feb 8, 2012 at 20:27

6 Answers 6

23

I wrote an example for unit-testing canvas and other image-y types with Jasmine and js-imagediff.

Jasmine Canvas Unit Testing

I find this to be better than making sure specific methods on a mock Canvas have been invoked because different series of methods may produce the same method. Typically, I will create a canvas with the expected value or use a known-stable version of the code to test a development version against.

0
8

As discussed in the question comments it's important to check that certain functions have been invoked with suitable parameters. pcjuzer proposed the usage of proxy pattern. The following example (RightJS code) shows one way to do this:

var Context = new Class({
    initialize: function($canvasElem) {
        this._ctx = $canvasElem._.getContext('2d');

        this._calls = []; // names/args of recorded calls

        this._initMethods();
    },
    _initMethods: function() {
        // define methods to test here
        // no way to introspect so we have to do some extra work :(
        var methods = {
            fill: function() {
                this._ctx.fill();
            },
            lineTo: function(x, y) {
                this._ctx.lineTo(x, y);
            },
            moveTo: function(x, y) {
                this._ctx.moveTo(x, y);
            },
            stroke: function() {
                this._ctx.stroke();
            }
            // and so on
        };

        // attach methods to the class itself
        var scope = this;
        var addMethod = function(name, method) {
            scope[methodName] = function() {
                scope.record(name, arguments);

                method.apply(scope, arguments);
            };
        }

        for(var methodName in methods) {
            var method = methods[methodName];

            addMethod(methodName, method);
        }
    },
    assign: function(k, v) {
        this._ctx[k] = v;
    },
    record: function(methodName, args) {
        this._calls.push({name: methodName, args: args});
    },
    getCalls: function() {
        return this._calls;
    }
    // TODO: expand API as needed
});

// Usage
var ctx = new Context($('myCanvas'));

ctx.moveTo(34, 54);
ctx.lineTo(63, 12);

ctx.assign('strokeStyle', "#FF00FF");
ctx.stroke();

var calls = ctx.getCalls();

console.log(calls);

You can find a functional demo here.

I have used a similar pattern to implement some features missing from the API. You might need to hack it a bit to fit your purposes. Good luck!

1
  • Heh, I saw you post this on twitter and was wondering why you had written something like this :) Apr 26, 2011 at 16:55
1

I make really simple canvases and test them with mocha. I do it similarly to Juho Vepsäläinen but mine looks a little simpler. I wrote it in ec2015.

CanvasMock class:

import ContextMock from './ContextMock.js'

export default class {
  constructor (width, height)
  {
    this.mock = [];
    this.width = width;
    this.height = height;
    this.context = new ContextMock(this.mock);
  }

  getContext (string)
  {
    this.mock.push('[getContext ' + string + ']')
    return this.context
  }
}

ContextMock class:

export default class {
  constructor(mock)
  {
    this.mock = mock
  }

  beginPath()
  {
    this.mock.push('[beginPath]')
  }

  moveTo(x, y)
  {
    this.mock.push('[moveTo ' + x + ', ' + y + ']')
  }

  lineTo(x, y)
  {
    this.mock.push('[lineTo ' + x + ', ' + y + ']')
  }

  stroke()
  {
    this.mock.push('[stroke]')
  }
}

some mocha tests that evaluates the functionality of the mock itself:

describe('CanvasMock and ContextMock', ()=> {
    it('should be able to return width and height', ()=> {
      let canvas = new CanvasMock(500,600)
      assert.equal(canvas.width, 500)
      assert.equal(canvas.height, 600)
    })
    it('should be able to update mock for getContext', ()=> {
      let canvas = new CanvasMock(500,600)
      let ctx = canvas.getContext('2d')
      assert.equal(canvas.mock, '[getContext 2d]')
    })
})

A mocha tests that evaluates the functionality of a function that returns a canvas:

import Myfunction from 'MyFunction.js'

describe('MyFuntion', ()=> {
it('should be able to return correct canvas', ()=> {
  let testCanvas = new CanvasMock(500,600)
  let ctx = testCanvas.getContext('2d')
  ctx.beginPath()
  ctx.moveTo(0,0)
  ctx.lineTo(8,8)
  ctx.stroke()
  assert.deepEqual(MyFunction(new CanvasMock(500,600), 8, 8), canvas.mock, [ '[getContext 2d]', '[beginPath]', '[moveTo 0, 0]', [lineTo 8, 8]', '[stroke]' ])
})

so in this example myfunction takes the canvas you passed in as an argument ( Myfunction(new CanvasMock(500,600), 8, 8) ) and writes a line on it from 0,0 to whatever you pass in as the arguments ( Myfunction(new CanvasMock(500,600),** 8, 8**) ) and then returns the edited canvas.

so when you use the function in real life you can pass in an actual canvas, not a canvas mock and then it will run those same methods but do actual canvas things.

read about mocks here

0

Since the "shapes" and "lines" drawn on a canvas are not actual objects (it's like ink on paper), it would be very hard (impossible?) to do a normal unit test on that.

The best you can do with standard canvas it analyze the pixel data (from the putImageData/getImageData. Like what bedraw was saying).

Now, I haven't tried this yet, but it might be more what you need. Cake is a library for the canvas. It's using alot of the putImageData/getImageData. This example might help with what you are trying to do with a test.

Hope that helps answer your question.

1
  • As tedious as it is, one can write a mock Context object for the drawing code to depend on and test that the proper calls are made to the Context object.
    – mlibby
    Nov 1, 2011 at 13:29
0

I've been looking at canvas testing recently and I've now thought about a page that allows comparing the canvas to a "known good" image version of what the canvas should look like. This would make a visual comparison quick and easy.

And maybe have a button that, assuming the output is OK, updates the image version on the server (by sending the toDataUrl() output to it). This new version can then be used for future comparisons.

Not exactly (at all) automated - but it does make comparing the output of your code easy.

Edit:

Now I've made this:

Utility to test canvas output

The left chart is the real canvas whilst the right is an image stored in a database of what it should look like (taken from when I know the code is working). There'll be lots of these to test all (eventually) aspects of my code.

0

From a developer's point of view the canvas is almost write-only because once drawn it's difficult to programmatically get something useful back. Sure one can do a point by point recognition but that's too tedious and such tests are hard to be written and maintained.

It's better to intercept the calls made to a canvas object and investigate those. Here are a few options:

  1. Create a wrapper object that records all the calls. Juho Vepsäläinen posted a such example.
  2. If possible use a library like frabric.js that offers a higher level of abstraction for drawing. The "drawings" are JS objects that can be inspected directly or converted to SVG which is easier to inspect and test.
  3. Use Canteen to intercept all the function calls and attribute changes of a canvas object. This is similar with option 1.
  4. Use Canteen with rabbit which offers you a few Jasmine custom matchers for size and alignment and a function getBBox() that can be used to determine the size and the position of the stuff being drawn on the canvas.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.