Test driving your visualization – SVG rendering

Now we have the basic skeleton of our bar chart object created, and we feel that we are ready to try to render something, so in this second iteration we will try to generate the svg:svg element.

How to do it...

Rendering the svg:svg element should not only simply add the svg:svg element to the HTML body, but also translate the width and height setting on our chart object to proper SVG attributes. Here is how we express our expectation in our test cases:

describe('.render', function () {
        describe('svg', function () {
            it('should generate svg', function () {
                chart.render();
                expect(svg()).not.toBeEmpty();
            });

            it('should set default svg height and width', 
              function () {
                chart.render();
                expect(svg().attr('width')).toBe('500'),
                expect(svg().attr('height')).toBe('350'),
            });

            it('should allow changing svg height and width', 
              function () {
                chart.width(200).height(150).render();
                expect(svg().attr('width')).toBe('200'),
                expect(svg().attr('height')).toBe('150'),
            });
        });
});

function svg() {
    return div.select('svg'),
}

How it works...

At this point, all of these tests will fail since we don't even have the render function; however, it clearly articulates that we expect the render function to generate the svg:svg element and setting the width and height attributes correctly. The second test case also makes sure that if the user does not provide the height and width attributes we will supply a set of default values. Here is how we will implement the render method to satisfy these expectations:

...
var _parent = p, _width = 500, _height = 350
        _data;

    that.render = function () {
        var svg = _parent
            .append("svg")
            .attr("height", _height)
            .attr("width", _width);
    };

    that.width = function (w) {
        if (!arguments.length) return _width;
        _width = w;
        return that;
    };

    that.height = function (h) {
        if (!arguments.length) return _height;
        _height = h;
        return that;
};
...

At this point our SpecRunner.html is once again all green and happy. However, it's still not doing much since all it does is generate an empty svg element on the page and not even use the data at all.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset