Prototype Tests

by Douglas Ludlow

HTML

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/qunit/1.14.0/qunit.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/qunit/1.14.0/qunit.js"></script>
  <div id="qunit"></div>
  <div id="qunit-fixture"></div>

JavaScript

function Animal(name) {
    this.name = name || 'unknown';
}

Animal.prototype.sound = function() {
    return '...';
}

function Dog(name, breed) {
    this.name = name || 'unknown';
    this.breed = breed || 'unknown';
    this.bark = function() {
        return 'Bark!';
    };
}

Dog.prototype = new Animal;
Dog.prototype.sound = function() {
  return this.bark();  
};

function Pointer() {
    this.point = function() {
        return 'Pointing...';
    };
}

Pointer.prototype = new Dog;

QUnit.test('Animal tests', function(assert) {
    var animal = new Animal();
    assert.ok(animal instanceof Animal, 'animal is an instance of Animal');
    assert.ok(!(animal instanceof Dog), 'animal is NOT an instance of Dog');
    assert.equal(animal.sound(), '...', 'animal\'s sound is "..."');
});

QUnit.test('Dog tests', function(assert) {
    var dog = new Dog('Fido', 'Beagle');
    
    assert.ok(dog instanceof Dog, 'dog is an instance of Dog');
    assert.ok(dog instanceof Animal, 'dog is an instance Animal');
    assert.equal(dog.name, 'Fido', 'dog\'s name is assigned');
    assert.equal(dog.breed, 'Beagle', 'dog\'s breed is assigned');
    assert.equal(dog.sound(), 'Bark!', 'Animal\'s sound is overridden by Dog');
});

QUnit.test('Pointer tests', function(assert) {
    var pointer = new Pointer('Hunter');
    assert.ok(pointer instanceof Pointer, 'pointer is an instance of Pointer');
    assert.ok(pointer instanceof Dog, 'pointer is an instance of Dog');
    assert.ok(pointer instanceof Animal, 'pointer is an instance Animal');
    assert.equal(pointer.sound(), 'Bark!', 'Pointer uses Dog\'s sound');
    assert.equal(pointer.name, 'Hunter', 'name is assigned');
});