HTML Canvas Unit testing

前端 未结 6 846
既然无缘
既然无缘 2020-12-08 13:46

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

6条回答
  •  感情败类
    2020-12-08 14:29

    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.

提交回复
热议问题