Jasmine cheat sheet - 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

describe('built-in matchers', function () {

    describe('toEqual', function () {
        // toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc.
        it('passes if subject and expectation are equivalent', function () {
            expect('Hello World!').toEqual('Hello World!');
            expect('Hello World!').not.toEqual('Goodbye!');
            expect([1, 2, 3]).toEqual([1, 2, 3]);
            expect(1).toEqual(1);
            expect({
                foo: 1
            }).toEqual({
                foo: 1
            });
        });
    });

    describe('toBe', function () {
        // compares the actual to the expected using ===
        it('passes if subject and expectation are the same object', function () {
            var myObj = {
                prop: 'value'
            };
            expect(myObj).toBe(myObj);
            expect(true).toBe(true);
            expect(1).toBe(1);
            expect('string value').toBe('string value');
            // Demonstrate the difference between toBe and toEqual 
            // not.toBe
            expect({
                foo: 1
            }).not.toBe({
                foo: 1
            });
            // toEqual 
            expect({
                foo: 1
            }).toEqual({
                foo: 1
            });
        });
    });

    describe('toMatch', function () {
        it('compares the actual to the expected using a regular expression', function () {
            expect('Hello Jasmine').toMatch(/jasmine/i);
            expect('phone: 123-45-67').toMatch(/\d{3}-\d{2}-\d{2}/);
            // Using a variable in a regexp
            var postfix = 'long message';
            expect('This is my long Message').toMatch(new RegExp('my ' + postfix, "i"));
        });
    });

    describe('toBeDefined', function () {
        it('passes if subject is not undefined', function () {
            expect({}).toBeDefined();
           ...