javascript - How can I test a Backbone subclass in Mocha without duplicating tests for the superclass? -
say have couple of backbone models, rectangle , triangle, each extend polygon.
var polygon = backbone.model.extend({ defaults: { width: 100, height: 100, rotation: 0 }, rotate: function (degrees) { var oldrotation = this.get('rotation'); var newrotation = (oldrotation + degrees) % 360; this.set('rotation', newrotation); return newrotation; } }); var rectangle = polygon.extend({ area: function (degrees) { return this.get('width') * this.get('height'); } }); var triangle = polygon.extend({ area: function (degrees) { return this.get('width') * this.get('height') / 2; } }
i want test rectangle , triangle , ensure each of them independently implements rotate
correctly, though know (for now) both inherit implementation of rotate
polygon.
what don't want create separate unit tests rectangle , triangle exact duplicates of 1 another. in mocha, how can write test rotate
, reuse in unit tests both triangle , rectangle?
here unit tests. note duplicate 'rotates 45 degrees' test.
describe('a rectangle', function () { var r = new rectangle({width: 50, height: 10, rotation: 90}); it('correctly calculates area', function () { expect(r.area()).to.equal(500); }); it('rotates 45 degrees', function () { expect(r.rotate(45)).to.equal(135); }); }); describe('a triangle', function () { var t = new triangle({width: 50, height: 10, rotation: 90}); it('correctly calculates area', function () { expect(t.area()).to.equal(250); }); it('rotates 45 degrees', function () { expect(t.rotate(45)).to.equal(135); }); });
the answer obvious after writing out. can create function encapsulate tests polygon.
var describeapolygon = function (name, p) { describe(name, function () { it('rotates 45 degrees', function () { expect(p.rotate(45)).to.equal(135); }); }); };
and use in tests rectangle , triangle.
describe('a rectangle', function () { var r = new rectangle({width: 50, height: 10, rotation: 90}); describeapolygon('a rectangle', r); it('correctly calculates area', function () { expect(r.area()).to.equal(500); }); }); describe('a triangle', function () { var t = new triangle({width: 50, height: 10, rotation: 90}); describeapolygon('a triangle', t); it('correctly calculates area', function () { expect(t.area()).to.equal(250); }); });
that's cleanest solution i've been able find. i'm curious if else has tackled problem , come different.
Comments
Post a Comment