martes, 23 de junio de 2015

Jasmine. Matchers (I) - toBe, toEqual, toMatch, toBeDefined, toBeUndefined, toBeNull

Artículos anteriores:
Jasmine. Introducción. Creando el primer test

Jasmine implementa un importante número de funciones de comprobación o matchers.

Los matchers nos permiten comprobar si un valor cumple una condición determinada, o si no la cumple anteponiendo la palabra clave not al matcher.

Vamos a repasar estos matchers viendo ejemplos de su funcionamiento.

toBe


El matcher toBe realiza una comparación entre el valor actual y el esperado utilizando el operador ===.

Podemos crear algunos tests para comprobar el funcionamiento del matcher.

describe("toBe", function () {

    it("Mismo valor y mismo tipo", function () {
        var value = 5;
        expect(value).toBe(5);
    });

    it("No es lo mismo si el tipo es distinto", function () {
        var value = 5;
        expect(value).not.toBe("5");
    });

    it("null no es lo mismo que undefined", function () {
        var value = null;
        expect(value).not.toBe(undefined);
    });

    it("Dos objetos deben ser el mismo", function () {
        function foo(val1, val2) {
            this.a = val1;
            this.a = val2;
        }

        var value = { a: 10, b: 20 };
        var expectedValue = { a: 10, b: 20 };
        expect(value).not.toBe(expectedValue);

        expectedValue = value;
        expect(value).toBe(expectedValue);

        value = new foo(10, 20);
        expectedValue = new foo(10, 20);
        expect(value).not.toBe(expectedValue);
        
        expectedValue = value;
        expect(value).toBe(expectedValue);

    });
});

Resultado tests toBe

toEqual


Comprueba que el valor actual es igual al esperado, aunque no necesariamente tiene que hacer referencia al mismo objeto.

A diferencia del matcher toBe, cuando dos objetos tienen las mismas propiedades y éstas tienen los mismos valores se consideran iguales.
describe("toEqual", function () {

    it("Mismo valor y mismo tipo", function () {
        var value = 5;
        expect(value).toEqual(5);
    });

    it("No es lo mismo si el tipo es distinto", function () {
        var value = 5;
        expect(value).not.toEqual("5");
    });

    it("null no es lo mismo que undefined", function () {
        var value = null;
        expect(value).not.toEqual(undefined);
    });

    it("Dos objetos no tiene porqué ser el mismo", function () {
        function foo(val1, val2) {
            this.a = val1;
            this.a = val2;
        }

        var value = { a: 10, b: 20 };
        var expectedValue = { a: 10, b: 20 };
        expect(value).toEqual(expectedValue);

        expectedValue = value;
        expect(value).toEqual(expectedValue);

        value = new foo(10, 20);
        expectedValue = new foo(10, 20);
        expect(value).toEqual(expectedValue);

        expectedValue = value;
        expect(value).toEqual(expectedValue);

    });

});

Resultado tests toEqual

toMatch


Comprueba si el valor actual cumple con una expresión regular.

describe("toMatch", function () {

    var value = "Asier Villanueva";

    it("\"Asier Villanueva\" cumple con la expresión regular /^.*\\s.*$/", function () {
        expect(value).toMatch(/^.*\s.*$/);
    });

    it("\"Asier Villanueva\" no cumple con la expresión regular /^\\d*$/", function () {
        expect(value).not.toMatch(/^\d*$/);
    })
});

Resultados tests toMatch

toBeDefined


Permite comprobar que una variable está "definida", es decir, que tiene un valor asignado, aunque dicho valor sea null. Lo que hace en realidad es comprobar que el valor no sea undefined.

describe("toBeDefined", function () {
    var definedValue = 4;
    var nullValue = null;
    var undefinedValue;

    it("Comprueba que el valor está definido", function () {
        expect(definedValue).toBeDefined();
    });

    it("Una variable con valor null está definida", function () {
        expect(nullValue).toBeDefined();
    });

    it("Una variable no incializada no está definida", function () {
        expect(undefinedValue).not.toBeDefined();
    });

});

Resultado tests toBeDefined

toBeUndefined


Comprueba que una variable no esté "definida" o, lo que es lo mismo, su valor es undefined.
Es equivalente a not.toBeDefined.

describe("toBeUndefined", function () {
    var definedValue = 4;
    var nullValue = null;
    var undefinedValue;

    it("Una variable inicializada no es undefined", function () {
        expect(definedValue).not.toBeUndefined();
    });

    it("Una variable con valor null no se considera no definida", function () {
        expect(nullValue).not.toBeUndefined();
    });

    it("Una variable no incializada no está definida", function () {
        expect(undefinedValue).toBeUndefined();
    });

});

Resultado tests toBeUndefined

toBeNull


toBeNull comprueba que la variable tiene asignado un valor null. Una variable no inicializada no se evalúa como null.
describe("toBeNull", function () {
    var definedValue = 4;
    var nullValue = null;
    var undefinedValue;

    it("Una variable inicializada con un valor no nulo no es null", function () {
        expect(definedValue).not.toBeNull();
    });

    it("Commprueba que el valor es null", function () {
        expect(nullValue).toBeNull();
    });

    it("Una variable no incializada no tiene valor null", function () {
        expect(undefinedValue).not.toBeNull();
    });

});

Resultado tests toBeNull


Artículo siguiente:
Jasmine. Matchers (II) - toBeTruthy, toBeFalsy, toContain, toBeLessThan, toBeGreaterThan, toBeCloseTo

No hay comentarios:

Publicar un comentario