Jasmine - Custom Matchers

Demonstrating Jasmine custom matchers

by munir

HTML

<script src="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine.js"></script>
<script src="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine-html.js"></script>
<link rel="stylesheet" href="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine.css">

JavaScript

//Munir

var Person = function (firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
}

describe('custom matchers', function () {

    beforeEach(function () {
        this.addMatchers({
            toHaveFirstAndLastName: function () {
                return (this.actual.firstName !== jasmine.undefined && this.actual.lastName !== jasmine.undefined);
            }
        })
    });

    describe('Person', function () {

        it('has a name', function () {
            var p = new Person('John', 'Doe');
            expect(p).toHaveFirstAndLastName();
            var elvis = new Person('Elvis');
            expect(elvis).not.toHaveFirstAndLastName();
        });
    });
});

// Jasmine spec runner
(function () {
    var jasmineEnv = jasmine.getEnv();
    jasmineEnv.updateInterval = 1000;

    var trivialReporter = new jasmine.TrivialReporter();

    jasmineEnv.addReporter(trivialReporter);

    jasmineEnv.specFilter = function (spec) {
        return trivialReporter.specFilter(spec);
    };

    var currentWindowOnload = window.onload;

    window.onload = function () {
        if (currentWindowOnload) {
            currentWindowOnload();
        }
        execJasmine();
    };

    function execJasmine() {
        jasmineEnv.execute();
        trivialReporter.outerDiv.className += ' show-passed';
    }

})();