j0ker
j0ker

Reputation: 4139

How to test a JavaScript SVG/Canvas application?

We are evaluating future work on a graphical JavaScript application that uses HTML5-Technologies like SVG and Canvas. One big problem (as with all UI centered applications) is how to write tests for all the functionality. It would not be sufficient if we could only test the JavaScript logic, but we also need to know, if the interface is working.

So we would at least need something like Selenium that enables us to interact with SVG/Canvas. Also, of course, there must be some kind of framework to write ordinary unit tests for the logic behind the drawing. And it should be free to use.

Is there something like that available? Also, since we have no previous experience in testing of this kind of software at all, we would appreciate any kind of tips how to solve our problem and how this is done usually. I trust, we are not the first ones thinking about that.

Thanks in advance!

Upvotes: 3

Views: 1255

Answers (1)

codebox
codebox

Reputation: 20254

I appreciate this doesn't fully answer your question, but with regard to unit testing, JavaScripts loose typing makes it very easy to produce mock objects to ensure that your application logic is interacting with (for example) a Canvas element correctly. For example, if you have a function which draws something on a cavas:

function drawSomething(canvas){
    var ctx = canvas.getContext('2d');
    ctx.fillRect(10, 10, 55, 50);
}

then you could test it like this:

function testdrawSomething(){
    var mockCanvas = {};
    var mockCtx = {};
    mockCanvas.getContext = function(){
        return mockCtx;
    };
    mockCtx.fillRect = function(a,b,c,d){
        // test values here
    }
    drawSomething(mockCanvas);
}

I have used RhinoUnit, together with this approach, to produce some quite comprehensive unit tests for UI-intensive HTML5 sites - and if you write your code carefully (pass all references to DOM elements as arguments into the functions that you want to test) you can run all your unit tests outside a browser, allowing them to be part of a CI pipeline.

Obviously you will want to run some in-browser tests as well, which is where Selenium comes in.

Upvotes: 4

Related Questions